使用LEFT JOIN和GROUP BY在日期和SUM之间进行过滤

时间:2017-09-15 16:22:12

标签: mysql

在以下查询中,我希望始终显示行,即使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

2 个答案:

答案 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.salesVARCHAR,而您的示例数据中也为空。

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;

Fiddle