[英]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-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
它不能得到像我真正想要的結果。 這個結果可以從我的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
這是編程中一個眾所周知的問題。 有幾種解決方案。
使用PHP查看結果,並在結果數組中填充缺少的日期。
AS sagi建議,創建一個單獨的表,其中包含應用程序使用的天數范圍內的所有日期,然后您可以使用您的查詢加入該表。 其中一個問題是,如果您在將來或過去突然錯過了幾天,您不得不在此表中添加更多天數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.