4

Can I list somehow the dates of last 30 days in MySQL? Not from a table!

For example I think about like this:

SELECT date WHERE date BETWEEN SUBDATE(NOW(), INTERVAL 30 DAY) AND NOW();

Is that possible?

Vldb.User
  • 21
  • 4
netdjw
  • 5,419
  • 21
  • 88
  • 162

2 Answers2

7

I hacked this together from someone else's code, but it seems to work:

SELECT DATE_FORMAT(m1, '%d %b %Y')
FROM (
SELECT SUBDATE( NOW() , INTERVAL 30 DAY) + INTERVAL m DAY AS m1
FROM (
select @rownum:=@rownum+1 as m from
(select 1 union select 2 union select 3 union select 4) t1,
(select 1 union select 2 union select 3 union select 4) t2,
(select 1 union select 2 union select 3 union select 4) t3,
(select 1 union select 2 union select 3 union select 4) t4,
(select @rownum:=-1) t0
) d1
) d2 
WHERE m1 <= now()
ORDER BY m1

The original code by valex is here:

How to get a list of months between two dates in mysql

Community
  • 1
  • 1
The Blue Dog
  • 2,475
  • 3
  • 19
  • 25
0

You can do this the "explicit" way. That is, generate a series of numbers and calculate the date:

select date(date_sub(now(), interval n.n day) as thedate
from (select 1 as n union all
      select 2 union all
      . . .
      select 30
     ) n
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786