MYSQL计数,LEFT OUTER JOIN,简单情况下0计数

时间:2014-06-03 10:39:34

标签: mysql join count zero outer-join

考虑以下两个样本表

表1:'用户'

ID    REGISTER_TIME    FIRSTNAME    LASTNAME    OPERATION_ID

1     1401789877       John         Doe         29
2     1401789879       Jack         Doe         29
3     1401789878       Pete         Doe         29

(注意,register_time列存储为INT(11))

表2:'calendar_days'

ID    DAY
1     2011-01-01
...   ....
n     2030-31-12

我有以下MySQL查询,它运行良好:

SELECT d.day, COUNT(d.day)
FROM calendar_days AS d
LEFT OUTER JOIN users AS l ON DATE(FROM_UNIXTIME(l.`register_time`)) = d.day
WHERE l.`operation_id` = 29
GROUP BY d.day;

但它没有保持计数等于零的日子:

day;COUNT(d.day)

2014-05-07;1
2014-05-09;1
2014-05-12;11
2014-05-13;2713
2014-05-14;2631

我想要的是什么:

2014-05-07;1
**2014-05-08;0**
2014-05-09;1
2014-05-12;11
2014-05-13;2713
2014-05-14;2631

我觉得我离真相很近,我已经尝试过任何可能的左外连接,右外连接,仍然没有空洞的结果。

1 个答案:

答案 0 :(得分:5)

由于您在联接表上使用条件,因此where子句会将left join变为inner join。尝试

SELECT d.day, COUNT(d.day)
FROM calendar_days AS d
LEFT OUTER JOIN users AS l ON DATE(FROM_UNIXTIME(l.`register_time`)) = d.day
                           AND l.`operation_id` = 29
GROUP BY d.day;