MySQL select 行,其中每一天的日期范围

MySQL select rows with dates range for each days of the range

我有一个 table 包含范围如下的事件 :

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

我想 select 所有行,但加入范围内的日期,所以我可以为范围内每一天的每个事件创建 X 行。 结果应该来自我的示例 table :

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

如果您是 运行 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

在早期版本中,典型的解决方案包括 table 个数字。这是一种最多可处理 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

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

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