我做了一些研究并了解了 COALESCE(sum(num), 0)
函数。问题是我发现的示例仅与使用一张表有关。
我正在计算第二个表的总和,如果第二个表中没有某个项目的记录,我仍然希望它显示在我的查询中并且总和为零。
SELECT note.user, note.product, note.noteID, note.note, COALESCE(sum(noteTable.Score), 0) as points
FROM note, noteTable
WHERE note.user <> 3 AND note.noteID = noteTable.noteID
只有当第二个表 noteTable 中有条目时,我才会收到结果。如果为注释添加了分数,我仍然希望它们以零分值显示在结果中。
表格示例:
注意
user | product | noteID |note
3 1 1 Great
3 2 2 Awesome
4 1 3 Sweet
笔记表
noteID | score
1 5
查询应该向我显示:
user | noteID | sum(points)
3 1 5
3 2 0
4 3 0
但我只得到这个:
user | noteID | sum(points)
3 1 5
最佳答案
http://sqlfiddle.com/#!9/aae812/2
SELECT
note.user,
note.product,
note.noteID, note.note,
COALESCE(sum(noteTable.Score),0) as points
FROM note
LEFT JOIN noteTable
ON note.noteID = noteTable.noteID
WHERE note.user <> 3
我想你应该添加:
GROUP BY note.noteid
如果您希望获得每个用户
的SUM
。因此您想要获取多于 1 条记录。
关于mysql - 如果第二个表中没有记录,则选择总和为零?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37380887/