sql - 从日期范围生成天数

标签 sql mysql datetime between

我想运行这样的查询

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

最佳答案

此解决方案不使用循环、过程或临时表。子查询生成最近 10,000 天的日期,并且可以扩展到您希望的任何时间。

select a.Date 
from (
    select curdate() - 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-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

关于sql - 从日期范围生成天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56844222/

相关文章:

mysql - MySQL 中 Many 2 Many 的 Order by 子句

javascript - 多表查询 + 指定返回值

java - 如何将 List<Object> 转换为逗号分隔的字符串

mysql - 计算所选列的总数

php - 从Unix时间戳创建PHP DateTime对象,在一行中设置时区

sql - 如何在 DB2 中查找表的主键的名称和值

mysql - 是否可以使用 INSERT 函数在查询表上插入一行?

mysql - 为什么插入和更新查询名称变量在 ColdFusion 中未定义

java - JPQL时间间隔

java - 为什么 Calendar 使用正确的时区返回错误的时间?