在以下查询中,我希望始终显示行,即使SUM结果为0。
没有WHERE子句它可以正常工作,但是当我想在日期之间进行过滤时,不会返回任何结果。什么细节失败了?
SELECT tc.cars,
COALESCE(SUM(ts.sales),0) AS cars_sales
FROM tbl_cars tc
LEFT JOIN tbl_sales ts ON tc.id_cars = ts.id_cars
WHERE tc.recDate BETWEEN '2017-04-01' AND DATE_ADD( '2017-05-01' , INTERVAL 1 DAY)
GROUP BY tc.cars
ORDER BY tc.cars;
SQLFiddle:http://www.sqlfiddle.com/#!9/425e6d/1/0
答案 0 :(得分:2)
请改用:
SELECT tc.cars,
COALESCE(SUM(ts.sales),0) AS cars_sales
FROM tbl_cars tc
LEFT JOIN tbl_sales ts ON tc.id_cars = ts.id_cars
and tc.recDate BETWEEN '2017-04-01' AND DATE_ADD( '2017-05-01' , INTERVAL 1 DAY)
GROUP BY tc.cars
ORDER BY tc.cars;
执行join
后,where
子句将根据where子句中提供的条件过滤整个数据集。由于您的数据集没有4月和5月的条目,因此需要空结果集。
答案 1 :(得分:1)
将条件放在JOIN上。此外,我认为您的意思是COUNT()
字段,因为您的架构中ts.sales
为VARCHAR
,而您的示例数据中也为空。
SELECT
tc.cars, COALESCE(COUNT(ts.sales), 0) AS cars_sales
FROM
tbl_cars tc
LEFT JOIN
tbl_sales ts ON tc.id_cars = ts.id_cars
AND tc.recDate BETWEEN '2010-04-01' AND DATE_ADD('2020-05-01', INTERVAL 1 DAY)
GROUP BY tc.cars
ORDER BY tc.cars;