首页  编辑  

不利用临时表生成指定日期范围内的所有天数

Tags: /MySQL/   Date Created:
http://stackoverflow.com/questions/2157282/generate-days-from-date-range
generate days from date range
mysql create date list between two dates
高票当选答案:
This solution uses no loops, procedures, or temp tables. The subquery generates dates for the last thousand days, and could be extended to go as far back or forward as you wish.
SELECT a.Date
FROM (
   SELECT '2010-01-01' + INTERVAL (a.a + (10 * b.a) + (100 * c.a) + (1000 * d.a)) DAY AS DATE
   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
   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 d
) a
WHERE a.Date BETWEEN '2010-01-01' AND '2015-08-24'
注意:上面的方法,最多只能支持1万天!其中2010-01-01为起始日期。
如果需要更多的天数,请在CROS JOIN后面增加更多的表e,如a, b, c, d,并且要在interval 中增加1000 * e。
这个查询的本质是,利用起始的一天,然后不断+1天循环生成需要的天数数据;