mysql一天一天地选择日期

时间:2016-11-27 09:15:36

标签: mysql sql

我的表格如下所示:

                      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-25以及2016-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表吗?

3 个答案:

答案 0 :(得分:3)

一种方法是在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

答案 1 :(得分:1)

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

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

答案 2 :(得分:1)

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

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

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