首页 > 开发 > MySQL > 正文

mysql 查询每个月发布的文章数。月份无数据显示为0。如何写SQL呢

2017-09-08 08:50:57  来源:网友分享
article表字段id (int),title (string),createtime (时间戳)

比如要查询2015年3月到2017年8月份,每个自然月发布的文章是多少篇。
月份没有发布文章的显示为0。
比如:

Array(    [0] => Array        (            [month] => 2015-3            [times] => 0        )    [1]=> Array        (            [month] => 2015-4            [times] => 4        )    [2]=> Array        (            [month] => 2015-5            [times] => 0        )            ...    [...]=> Array        (            [month] => 2017-8            [times] => 4        )     )

解决方案

前面两个兄弟都忽略了题主还要计算没有记录的月份吗?
解决题主的问题首先要构造一下自然月份表,然后才能跟article关联获取每个月的数据
创建一张自然月份表monlist:

create table monlist(id int auto_increment primary key,mon char(7));

构造自然月数据记录我这里有个方法,随便找一个大于12条记录的表,这里叫t_log,直接将记录插入monlist表sql如下:

insert into monlist(mon)select concat(yy,mon) dt from (    select bb.yy yy,case when mon<10 then concat('-0',mon) else concat('-',mon) end mon     from (        select @mon:=@mon+1 mon         from t_log,(select @mon:=0) a limit 12) aa         join (            select @yy:=@yy+1 yy             from t_log,(select @yy:=2010) b limit 10) bb) aaa order by yy,mon;

这里构造了2011-2020年的所有月份,格式为YYYY-MM,结构可以自己调整。
然后再获取指定时间段的每月文章数:

select a.mon,sum(case when b.id is null then 0 else 1 end) sum from monlist a left join article b on a.mon=date_format(b.createtime,'%Y-%m') where a.mon>='2015-03' and a.mon<='2017-08' group by a.mon;