[英]mysql select date day by day
I have table shown below : 我有如下表格:
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
from above table what I want to get is like this: 从上表我想得到的是这样的:
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
But, because there are only dates 2016-11-23
and 2016-11-25
and 2016-11-27
, when I query like this : 但是,因为只有
2016-11-23
和2016-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
It can't get result like what I really want to get. 它不能得到像我真正想要的结果。 Is that result possible from my
login
table? 这个结果可以从我的
login
表中获得吗?
One way is to generate all days before JOIN 一种方法是在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
Use a derived table with the wanted dates : 使用带有所需日期的派生表:
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
This is a very well known problem in programming. 这是编程中一个众所周知的问题。 There are several solutions.
有几种解决方案。
Go over the result with PHP, and fill the missing days in the resulting array. 使用PHP查看结果,并在结果数组中填充缺少的日期。
AS sagi proposed, create a separate table that contains all the dates in the range of days your application works with, then you can JOIN that table with your query. AS sagi建议,创建一个单独的表,其中包含应用程序使用的天数范围内的所有日期,然后您可以使用您的查询加入该表。 One of the issues is that from time to time you have to add more days to this table, if you suddenly have missing days in future or in past.
其中一个问题是,如果您在将来或过去突然错过了几天,您不得不在此表中添加更多天数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.