我在MySQL中有两个这样的表:
LOCAL
id | name
GRADE (grades given by users for each location)
id | id_local | grade
当我列出每个本地人获得的平均成绩,而本地人尚未获得任何成绩时,它不会出现在列表中
我的代码就是这样
SELECT *, AVG(grade.grade) AS 'grade' FROM local
LEFT JOIN grade ON local.id = grade.id_local
GROUP BY grade.id_local
答案 0 :(得分:2)
您需要按 first 表中的列进行汇总:
SELECT l.*, AVG(g.grade) AS grade
FROM local l LEFT JOIN
grade g
ON local.id = g.id_local
GROUP BY l.id;
假设GROUP BY
是唯一的或SELECT l.*
中的主键(合理的假设),即使使用id
,local
也可以。
答案 1 :(得分:2)
您的问题是,您正在按grade.id_local
分组,并且当某个位置没有坡度时,该值为NULL
。您应该改为按local.id
分组。另外,您可能想将COALESCE
应用于AVG
值,以在没有成绩时将其设置为0。
SELECT local.id, local.name,
COALESCE(AVG(grade.grade), 0) AS 'grade'
FROM local
LEFT JOIN grade ON local.id = grade.id_local
GROUP BY local.id
输出(用于我的演示):
id name grade
1 here 4.5
2 there 0