繁体   English   中英

mysql一天一天地选择日期

[英]mysql select date day by day

我有如下表格:

                      login
          date                     user    
       2016-11-23                   1
       2016-11-23                   2
       2016-11-23                   3
       2016-11-25                   2
       2016-11-25                   5
       2016-11-27                   1

从上表我想得到的是这样的:

      date                   count(*)
   2016-11-21                   0
   2016-11-22                   0    
   2016-11-23                   3
   2016-11-24                   0
   2016-11-25                   2
   2016-11-26                   0
   2016-11-27                   1

但是,因为只有2016-11-232016-11-252016-11-27日期,当我这样查询时:

select date, count(*)
from login
where date between (current_date()-interval 7 day) and current_date()
group by date
order by date asc

它不能得到像我真正想要的结果。 这个结果可以从我的login表中获得吗?

一种方法是在JOIN之前生成所有日子

select GenDate, count(Date)
from login
right join
(select a.GenDate 
from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as GenDate
    from (select 0 as a 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) as a
    cross join (select 0 as a 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) as b
    cross join (select 0 as a 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) as c
) a
where a.GenDate between (current_date()-interval 7 day) and current_date())x
ON x.GenDate=login.Date
group by GenDate
order by GenDate asc

使用带有所需日期的派生表:

SELECT t.date, count(s.date)
FROM (SELECT '2016-11-21' as `date` UNION ALL
      SELECT '2016-11-22' as `date` UNION ALL
       ...) t
LEFT JOIN login s
 ON(t.date = s.date)
WHERE
    t.date between (current_date()-interval 7 day) and current_date()
GROUP BY t.date
ORDER BY t.date

这是编程中一个众所周知的问题。 有几种解决方案。

  1. 使用PHP查看结果,并在结果数组中填充缺少的日期。

  2. AS sagi建议,创建一个单独的表,其中包含应用程序使用的天数范围内的所有日期,然后您可以使用您的查询加入该表。 其中一个问题是,如果您在将来或过去突然错过了几天,您不得不在此表中添加更多天数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM