即使您当天没有任何内容,SELECT也会显示所有日期

时间:2018-08-07 11:28:52

标签: mysql wordpress mysql-workbench

我的查询是

SELECT DATE_FORMAT(post_date, '%Y-%m-%d') AS data_day
    , COUNT(*) AS count
FROM wpsa_posts
WHERE post_date >= DATE_ADD(CURDATE(),INTERVAL -7 DAY)
GROUP
    BY data_day
    ORDER BY data_day DESC
    LIMIT 7

查询结果如下:

enter image description here

如果我过去30天喜欢这个贡纳姆

enter image description here

我想显示所有日期,如果我输入7(出现在过去7天,如果这一天没有显示,则显示为0)

像我想要的例子: 我想显示所有像这样的日期:

data_day     ||   count ||
2018-08-07   ||   0 if nothing on this day
2018-08-08   ||   32
2018-08-09   ||   1
2018-08-10   ||   4
2018-08-11   ||   0
2018-08-12   ||   0
2018-08-13   ||   0

我想那样表演

1 个答案:

答案 0 :(得分:1)

您已经生成了日期值并与表格联接,然后可以计数

select date, count(post_date) from
(select  * from (
select 
 date_add('2018-07-17 00:00:00.000', INTERVAL n5.num*10000+n4.num*1000+n3.num*100+n2.num*10+n1.num DAY ) as date 
  from
(select 0 as num
   union all select 1
   union all select 2
   union all select 3
   union all select 4
   union all select 5
   union all select 6
   union all select 7
   union all select 8
   union all select 9) n1,
(select 0 as num
   union all select 1
   union all select 2
   union all select 3
   union all select 4
   union all select 5
   union all select 6
   union all select 7
   union all select 8
   union all select 9) n2,
(select 0 as num
   union all select 1
   union all select 2
   union all select 3
   union all select 4
   union all select 5
   union all select 6
   union all select 7
   union all select 8
   union all select 9) n3,
(select 0 as num
   union all select 1
   union all select 2
   union all select 3
   union all select 4
   union all select 5
   union all select 6
   union all select 7
   union all select 8
   union all select 9) n4,
(select 0 as num
   union all select 1
   union all select 2
   union all select 3
   union all select 4
   union all select 5
   union all select 6
   union all select 7
   union all select 8
   union all select 9) n5
) a
where date >'2018-07-17 00:00:00.000' and date < NOW()
) as t
left join wpsa_posts w on t.date=DATE_FORMAT(w.post_date, '%Y-%m-%d')
 WHERE date >= DATE_ADD(CURDATE(),INTERVAL -7 DAY)
 group by date