Get a list of dates between two dates

后端 未结 20 2108
醉梦人生
醉梦人生 2020-11-22 00:26

Using standard mysql functions is there a way to write a query that will return a list of days between two dates.

eg given 2009-01-01 and 2009-01-13 it would return

20条回答
  •  无人及你
    2020-11-22 00:59

    Borrowing an idea from this answer, you can set up a table with 0 through 9 and use that to generate your list of dates.

    CREATE TABLE num (i int);
    INSERT INTO num (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
    
    select affffdate('2009-01-01', numlist.id) as `date` from
    (SELECT n1.i + n10.i*10 + n100.i*100 AS id
       FROM num n1 cross join num as n10 cross join num as n100) as numlist
    where affffdate('2009-01-01', numlist.id) <= '2009-01-13';
    

    This will allow you to generate a list of up to 1000 dates. If you need to go larger, you can add another cross join to the inner query.

提交回复
热议问题