user7159879 user7159879 - 11 days ago 8
MySQL Question

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 :

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?

Answer

One way is to generate all days before 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