我试图根据与两列中每一列关联的位置返回两列的总数。 当我像这样使用 OR 语句时:
$query = "
SELECT
ec.ElecEnergy,
ec.GasEnergy,
ua.City,
SUM(ec.ElecEnergy) AS ecTotal,
SUM(ec.GasEnergy) AS gcTotal
FROM energyconsumption ec
INNER JOIN useraccount ua ON ec.User = ua.id
WHERE
ua.City ='London'
OR City ='Manchester'
OR City ='Luton'
OR City ='Newcastle'
OR City ='Birmingham'
OR City ='Blackburn'
GROUP BY ec.ElecEnergy, ec.GasEnergy, ua.City
ORDER BY ec.ID ASC
";
$result = mysqli_query($conn,$query);
$r = array();
if ($result->num_rows) {
while ($row = mysqli_fetch_array($result)) {
array_push($r, array(
'ElecConsump' => $row['ecTotal'],
'GasConsump' => $row['gcTotal'],
'Location' => $row['City']
));
}
}
echo json_encode(array('results' => $r));
它只是返回我数据库中的所有内容。我想要的是基于我列出的每个城市的列的总和。
我不确定我做错了什么。
您只想将
city
包含在 group by
中,而不是包含您正在聚合的列。 请记住,group by
中的列定义了要返回的行,每行上都有唯一的组合。
另外,使用
in
。 。 。编写和阅读更简单:
SELECT ua.City, SUM(ec.ElecEnergy) AS ecTotal, SUM(ec.GasEnergy) AS gcTotal
FROM energyconsumption ec INNER JOIN
useraccount ua
ON ec.User = ua.id
WHERE ua.City IN ('London', 'Manchester', 'Luton', 'Newcastle', 'Birmingham', 'Blackburn')
GROUP BY ua.City
ORDER BY ua.City ASC;
请注意,我还更改了
ORDER BY
子句 - 假设您要为每个城市返回一行。
如果您想要所有城市的总计,那么:
GROUP BY
和 ORDER BY
子句。ua.city
中删除 SELECT
。