如何选择&按天分组来自数据库的数据,但也包括没有条目的天数。在这种情况下,该值将为0.
如果不能使用MySQL,也可以使用PHP。
这是我目前所拥有的:
SELECT DATE_FORMAT(date, '%Y-%m-%d') AS the_date
, COUNT(*) AS count
FROM table
WHERE date BETWEEN DATE_FORMAT('2016-11-28', '%Y-%m-%d') AND DATE_FORMAT('2016-12-05', '%Y-%m-%d')
GROUP
BY the_date
答案 0 :(得分:1)
在PHP中添加缺少的日期可能更简单。在MySQL中,您需要从某个地方获取日期。通常,数据库具有包含此信息的“日历”表。如果你有一个,那么你想做的就是这样:
SELECT DATE_FORMAT(c.date, '%Y-%m-%d') AS the_date, COUNT(t.date) AS count
FROM Calendar c LEFT JOIN
table t
ON c.date = t.date
WHERE c.date BETWEEN '2014-11-28' AND '2014-12-05' -- MySQL recognizes strings in the format of YYYY-MM-DD as dates when needed
GROUP BY the_date;
如果您没有这样的表,可以为查询创建一个表:
SELECT DATE_FORMAT(c.date, '%Y-%m-%d') AS the_date, COUNT(t.date) AS count
FROM (SELECT date('2014-11-28') as date UNION ALL
SELECT date('2014-11-29') as date UNION ALL
SELECT date('2014-11-30') as date UNION ALL
SELECT date('2014-12-01') as date UNION ALL
SELECT date('2014-12-02') as date UNION ALL
SELECT date('2014-12-03') as date UNION ALL
SELECT date('2014-12-04') as date UNION ALL
SELECT date('2014-12-05') as date
) c LEFT JOIN
table t
ON c.date = t.date
GROUP BY the_date;
这适用于少数日期,但对于跨越数月或数年的范围而言效果不佳。