MySQL GROUP BY日期 - 如何在没有行时返回结果

时间:2011-05-13 06:42:12

标签: mysql group-by

我正在编写一个查询,以返回在一段时间内每天写的博客帖子数量。当某天没有博客记录时,我的问题就出现了。根据我的查询,完全跳过该日的结果。

这是我的疑问:

SELECT DATE(`posted`), COUNT(`id`) 
    FROM `blogs` WHERE `status` = 'active' 
    && `posted` BETWEEN `2011-01-01` AND `2011-05-01` 
    GROUP BY DATE(`posted`)

它返回类似于:

的内容
count | date
_________________
2     |  2011-01-01
5     |  2011-01-02
1     |  2011-01-04

请注意,它缺少2011-01-03,因为它没有任何帖子。

如何通过0个帖子显示那些日子?

2 个答案:

答案 0 :(得分:6)

您需要有一个表格,其中包含您要查询的所有日期,并按照以下方式执行操作...

SELECT DATE(D.`thedate`), COUNT(`id`)
FROM `datetable` D
LEFT JOIN `blogs` B
ON B.`posted` = D.`thedate`
WHERE `status` = 'active'     
&& D.`thedate` BETWEEN `2011-01-01` AND `2011-05-01`     
GROUP BY DATE(D.`thedate`)

答案 1 :(得分:0)

创建包含日期的表格(取自http://www.artfulsoftware.com/infotree/queries.php?&bw=1280#95):

-- Create a dummy view with 3 rows
create or replace view v3 as select 1 n union all select 1 union all select 1; 
-- create a second dummy view with 10 rows
-- By making joins with this view, you can create 100, 1000, ... rows
create or replace view v as select 1 n from v3 a, v3 b union all select 1; 
-- counter
set @n = 0; 
-- create date table
drop table if exists datetable; 
create table datetable(thedate date primary key); 
-- populate from start date
insert into datetable select cast('1970-1-1' + interval @n:=@n+1 day as date) as thedate 
from v a, v b, v c, v d, v e, v;