How to populate a table with a range of dates?

后端 未结 10 1254
夕颜
夕颜 2020-11-22 04:24

I need a MySQL table to hold ALL DATES between 2011-01-01 and 2011-12-31. I have created a table with one column names \"_date\", type DATE.

With what query can I po

10条回答
  •  广开言路
    2020-11-22 05:19

    Inspired by IvanD`s great number join i come to this:

    SELECT DATE_ADD('2015-10-21', INTERVAL c.number DAY)    AS DATE
    FROM 
    (
        SELECT singles + tens + hundreds+thousands number FROM 
        ( 
            SELECT 0 singles
            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
        ) singles JOIN 
        (
            SELECT 0 tens
            UNION ALL SELECT  10 UNION ALL SELECT  20 UNION ALL SELECT  30
            UNION ALL SELECT  40 UNION ALL SELECT  50 UNION ALL SELECT  60
            UNION ALL SELECT  70 UNION ALL SELECT  80 UNION ALL SELECT  90
        ) tens  JOIN 
        (
            SELECT 0 hundreds
            UNION ALL SELECT  100 UNION ALL SELECT  200 UNION ALL SELECT  300
            UNION ALL SELECT  400 UNION ALL SELECT  500 UNION ALL SELECT  600
            UNION ALL SELECT  700 UNION ALL SELECT  800 UNION ALL SELECT  900
        ) hundreds
         JOIN 
        (
            SELECT 0 thousands
            UNION ALL SELECT  1000 UNION ALL SELECT  2000 UNION ALL SELECT  3000
            UNION ALL SELECT  4000 UNION ALL SELECT  5000 UNION ALL SELECT  6000
            UNION ALL SELECT  7000 UNION ALL SELECT  8000 UNION ALL SELECT  9000
        ) thousands
        ORDER BY number DESC
    ) c  
    WHERE c.number BETWEEN 
    0 
    AND
    DATEDIFF('2016-10-08', '2015-10-21')
    

提交回复
热议问题