sql – 生成日期范围内的天数

我想运行一个查询

select ... as days where `date` is between '2010-01-20' and '2010-01-24'

并返回数据如:

days
----------
2010-01-20
2010-01-21
2010-01-22
2010-01-23
2010-01-24
此解决方案不使用循环,过程或临时表。子查询生成最后一千天的日期,并且可以根据需要扩展为前进或后退。

select a.Date 
from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.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
) a
where a.Date between '2010-01-20' and '2010-01-24' 

输出:

Date
----------
2010-01-24
2010-01-23
2010-01-22
2010-01-21
2010-01-20

性能注释

测试它here,性能惊人的好:上面的查询需要0.0009秒。

如果我们扩展子查询生成约。 100,000个数字(因此约274年的日期),它运行在0.0458秒。

顺便说一下,这是一个非常便携的技术,与大多数数据库工作与微小的调整。

SQL Fiddle example returning 1,000 days

http://stackoverflow.com/questions/2157282/generate-days-from-date-range

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:sql – 生成日期范围内的天数