如何获取两个日期之间的所有日期?

问题描述:

请看看我的books表:如何获取两个日期之间的所有日期?

books

+-----+----------+------------+------------+ 
| id | venue_id | from_date | to_date | 
+-----+----------+------------+------------+ 
| 1 | 8  | 2015-07-21 | 2015-07-28 | 
| 2 | 5  | 2015-08-03 | 2015-08-25 | 
+-----+----------+------------+------------+ 

我要查看from_dateto_date之间的所有日期安排venue_id = 8

我的输出应该是:

Array 
(
    [0] => Array 
     (
      [id] => 1 
      [venue_id] => 8 
      [today] => 2015-07-21 
     ) 
    [1] => Array 
     (
      [id] => 1 
      [venue_id] => 8 
      [today] => 2015-07-22 
     ) 
    [2] => Array 
     (
      [id] => 1 
      [venue_id] => 8 
      [today] => 2015-07-23 
     ) 
    [3] => Array 
     (
      [id] => 1 
      [venue_id] => 8 
      [today] => 2015-07-24 
     ) 
    [4] => Array 
     (
      [id] => 1 
      [venue_id] => 8 
      [today] => 2015-07-25 
     ) 
    [5] => Array 
     (
      [id] => 1 
      [venue_id] => 8 
      [today] => 2015-07-26 
     ) 
    [6] => Array 
     (
      [id] => 1 
      [venue_id] => 8 
      [today] => 2015-07-27 
     ) 
) 

today计算从from_date日期到to_date日期。但是我的想法对于那个查询是空白的。如何编写一个MySQL查询来获得像上面显示的输出结果?

+0

您的输出省略了结束日期 - 是否正确?因此,如果开始日期和结束日期相同,则不应显示数据。或者你确定结束日期总是晚于开始日期?你打算创建一个列表日期列表吗?然后它变得容易。否则,这并不容易。 –

以下查询应该用来获得所需的结果。 select * from books where venue_id = 8 and from_date> ='2015-07-21'and to_date < ='2015-07-27'

+0

2015-07-23如何生成记录? –

+0

你能告诉我什么是从今天开始计算的逻辑吗?to_date –

+0

我手边没有一个更好的解决方案,而不是一个包含与该应用程序相关的范围中每个日期的一行的表。即使您的数据可以回溯到罗马时代,并进入第10个千年结束时(不到500万行;更可能的是,少于500,000行),它并不是一个很大的表格。 –

我想下面的查询应该可以获取结果。虽然我还没有测试过这个查询。

select b.id,b.venue_id,d.date from books b 
join 
(select a.Date, "8" as venue_id2 
from (
select curdate() - INTERVAL (a.a + (10 * b.a) + (1000 * c.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 
) a 
where a.Date between '2010-01-20' and '2010-01-24') d on d.venue_id2 = b.venue_id and b.venue_id = 8 
+0

答案的一部分来自这篇文章http://*.com/questions/2157282/generate-days-from-date-range。以防万一你需要。 –

+0

我得到这个错误'#1064 - 你的SQL语法有错误; (选择curdate() - INTERVAL(aa +(10 * b'at line 2' – Chinmay235

+0

)对不起,对于您的MySQL服务器版本的手册,选择正确的语法来使用。我已经更正了现在的查询。 –