MySQL选择日期范围内每一天的日期范围的行

时间:2019-12-04 10:37:43

标签: mysql date

我有一个表,其中包含具有以下范围的事件:

id | title | start      | end
1  | Lorem | 2019-11-02 | 2019-11-03
2  | Ipsum | 2019-11-02 | 2019-11-02
3  | Dolor | 2019-11-08 | 2019-11-10
4  | Amet  | 2019-11-02 | 2019-11-04

我想选择所有行,但要加入范围中的日期,因此我可以为其范围内的每一天的每个事件设置X行。 结果应该来自我的示例表:

date        | id | title | start      | end
2019-11-02  | 1  | Lorem | 2019-11-02 | 2019-11-03
2019-11-02  | 2  | Ipsum | 2019-11-02 | 2019-11-02
2019-11-02  | 4  | Amet  | 2019-11-02 | 2019-11-04
2019-11-03  | 1  | Lorem | 2019-11-02 | 2019-11-03
2019-11-03  | 4  | Amet  | 2019-11-02 | 2019-11-04
2019-11-04  | 4  | Amet  | 2019-11-02 | 2019-11-04
2019-11-08  | 3  | Dolor | 2019-11-08 | 2019-11-10
2019-11-09  | 3  | Dolor | 2019-11-08 | 2019-11-10
2019-11-10  | 3  | Dolor | 2019-11-08 | 2019-11-10

我真的被困住了,不知道是否有可能...。谢谢您的帮助! 我在使用MySQL 5.7

2 个答案:

答案 0 :(得分:3)

如果运行的是MySQ 8.0,则这是直接的递归查询:

with recursive cte as (
    select start as date, id, title, start, end from mytable
    union all
    select date + interval 1 day, id, title, start, end from cte where date < end
)
select * from cte
order by date, id

Demo on DB Fiddle

date       | id | title | start      | end       
:--------- | -: | :---- | :--------- | :---------
2019-11-02 |  1 | Lorem | 2019-11-02 | 2019-11-03
2019-11-02 |  2 | Ipsum | 2019-11-02 | 2019-11-02
2019-11-02 |  4 | Amet  | 2019-11-02 | 2019-11-04
2019-11-03 |  1 | Lorem | 2019-11-02 | 2019-11-03
2019-11-03 |  4 | Amet  | 2019-11-02 | 2019-11-04
2019-11-04 |  4 | Amet  | 2019-11-02 | 2019-11-04
2019-11-05 |  3 | Dolor | 2019-11-05 | 2019-11-08
2019-11-06 |  3 | Dolor | 2019-11-05 | 2019-11-08
2019-11-07 |  3 | Dolor | 2019-11-05 | 2019-11-08
2019-11-08 |  3 | Dolor | 2019-11-05 | 2019-11-08

在早期版本中,典型的解决方案包括一个数字表。这是一种可处理长达4天的解决方案(您可以将子查询扩展更多):

select
    t.start + interval x.n day date,
    t.*
from 
mytable t
inner join (
    select 0 n union all select 1 union all select 2 union all select 3 union all select 4
) x on t.start + interval x.n day <= t.end
order by date, id

Demo on DB Fiddlde

答案 1 :(得分:0)

每天尝试使用带有日期字段的日历表。 这样,您可以在日历表的日期字段上进行左联接,如下所示:

SELECT 
calendar_table.date_field,
my_table.date,
my_table.id,
my_table.title,
my_table.start,
my_table.end
FROM calendar_table
LEFT JOIN my_table ON my_table.date = calendar_table.date_field