我需要此查询在count为0时返回结果,而不是仅生成空集。如何调整我的查询,以便生成下表,计数和适当的日期为“0”?
mysql> select count(test.id), date(insert_datetime) date
from db.table test where date(insert_datetime)='2015-08-17'
group by date(insert_datetime);
+--------------+------------+
| count(test.id) | date |
+--------------+------------+
| 42 | 2015-08-17 |
+--------------+------------+
1 row in set (0.14 sec)
mysql> select count(test.id), date(insert_datetime) date
from db.table test where date(insert_datetime)='2015-08-16'
group by date(insert_datetime);
Empty set (0.00 sec)
答案 0 :(得分:2)
这应该这样做:
SELECT theDate AS `date`, IFNULL(subC.theCount, 0) AS `theCount`
FROM (SELECT DATE(20150817) AS `theDate`) AS subD
LEFT JOIN (
SELECT COUNT(test.id) AS theCount, DATE(insert_datetime) AS `theDate`
FROM db.table AS test
WHERE insert_datetime BETWEEN 20150817000000 AND 20150817235959
GROUP BY theDate
) AS subC
USING (theDate)
;
正如另一位用户在现在删除的评论中暗示的那样:如果您需要这个日期范围,那么"所有日期" table可能比subD子查询更方便;使SELECT DATE(X) UNION SELECT DATE(Y) UNION SELECT DATE(Z) UNION SELECT DATE(etc...)
子查询很快就会变得荒谬。