如何在表格中显示多个两个日期之间的所有日期?

Pad*_*n J 5 mysql join date

我想显示特定记录的两个日期之间的所有日期

这是表:

ID Start_Date  End_Date
-------------------------
1  2013-01-14  2013-01-18
2  2013-02-01  2013-02-04
Run Code Online (Sandbox Code Playgroud)

现在我想获取从日期到日期之间的所有日期。

预期输出

ID Date
-------------
1  2013-01-14
1  2013-01-15
1  2013-01-16
1  2013-01-17
1  2013-01-18
2  2013-02-01
2  2013-02-02
2  2013-02-03
2  2013-02-04
Run Code Online (Sandbox Code Playgroud)

指导我编写查询而不创建任何额外的表。

我已经尝试过以下查询

select * from 
(select adddate('1970-01-01',t4*10000 + t3*1000 + t2*100 + t1*10 + t0) selected_date from
 (select 0 t0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 t1 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 t2 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 t3 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 t4 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
Run Code Online (Sandbox Code Playgroud)

它的单条记录工作正常。但我想从我的表中获取所有日期间隔

更新

我整天有 6 把椅子。因此,一个用户在 2013-01-14 到 2013-01-18 预订了 3 个字符,另一个人在 2013-01-17 到 2013-01-20 预订了 2 个字符。所以我的预期输出如下所示。

ID Date        Available
------------------------
1  2013-01-14          3
1  2013-01-15          3
1  2013-01-16          3
1  2013-01-17          5 
1  2013-01-18          5
1  2013-01-19          2
1  2013-01-20          2 
1  2013-01-21          2
Run Code Online (Sandbox Code Playgroud)

joa*_*olo 4

最简单的方法是有一个calendar表,按以下方式定义:

CREATE TABLE calendar
(
    a_day date PRIMARY KEY
) ;
Run Code Online (Sandbox Code Playgroud)

...并且充满了所有相关日期(即:从 1990 年 1 月 1 日到 2100 年 12 月 31 日的所有日期)。为了简单起见,我们只填写 2013 年:

INSERT INTO 
     calendar (a_day)
VALUES
    ('2013-01-01'),
    ('2013-01-02'),
    ('2013-01-03'),
    ('2013-01-04'),
    ('2013-01-05'),
    -- everything up to
    ('2013-12-31') ;
Run Code Online (Sandbox Code Playgroud)

此时,您可以有一个JOIN两个表;连接条件不是等式,而是范围条件:

SELECT
     t.id, c.a_day
FROM
     t
     JOIN calendar c ON c.a_day BETWEEN t.start_date AND t.end_date 
ORDER BY
     t.id, c.a_day ;
Run Code Online (Sandbox Code Playgroud)

...并得到

编号 | 一天     
-: | :---------
 1 | 2013-01-14
 1 | 2013-01-15
 1 | 2013-01-16
 1 | 2013-01-17
 1 | 2013-01-18
 2 | 2013-02-01
 2 | 2013-02-02
 2 | 2013-02-03
 2 | 2013-02-04

您可以在此处查看dbfiddle的所有设置