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

时间:2015-05-11 11:39:21

标签: mysql date datetime difference

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

这就是表格:

ID Start_Date End_Date

1 2013-01-14 2013-01-18
2 2013-02-01 2013-02-04

现在我希望获得从日期到日期之间的所有日期。

预期输出

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

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

我已经尝试过以下查询

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'

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

更新

我所有的日子都有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

2 个答案:

答案 0 :(得分:2)

怎么样

objects

<强> DEMO

答案 1 :(得分:1)

首先,我不知道您的具体用例,但这对于更多优化来说已经成熟。但是,这个怎么样?

 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') OR
      (selected_date between '2012-03-10' and '2012-03-15') OR
      (selected_date between '2012-04-10' and '2012-04-15')