MySQL SUM左连接显示所有类别,即使总和为0

时间:2018-07-08 15:05:46

标签: mysql sum left-join

我希望基于一组数据的分数之和选择所有类别,即使该组数据不包含类别也是如此。但是,无论我尝试什么,它始终只显示具有实际数据的类别。

我创建了以下SQLFiddle http://sqlfiddle.com/#!9/52a127/3

为便于查看,我将在此处粘贴select语句:

SELECT categories.id, IFNULL(SUM(raw_data.score), 0) as total
FROM categories
LEFT JOIN raw_data ON categories.id = raw_data.category_id
WHERE
(raw_data.quarter = '2018Q2' OR !raw_data.quarter) AND
raw_data.broker_id = 2 
GROUP BY categories.id
ORDER BY total DESC

从小提琴中可以看到,它仅显示2个类别,但我希望选择所有6个类别,对于没有结果的类别,将其选择为0。

感谢您的帮助,谢谢!

1 个答案:

答案 0 :(得分:3)

您需要将条件从WHERE移至ON子句:

SELECT categories.id, IFNULL(SUM(raw_data.score), 0) as total
FROM categories
LEFT JOIN raw_data ON categories.id = raw_data.category_id
  AND (raw_data.quarter = '2018Q2' OR !raw_data.quarter) 
  AND raw_data.broker_id = 2 
GROUP BY categories.id
ORDER BY total DESC;

SQLFiddle Demo