Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql select date day by day

Tags:

sql

mysql

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?

like image 607
user7159879 Avatar asked Nov 27 '16 09:11

user7159879


1 Answers

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
like image 151
Mihai Avatar answered Oct 13 '22 10:10

Mihai