2015-07-21 211 views
2

請看看我的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

您的輸出省略了結束日期 - 是否正確?因此,如果開始日期和結束日期相同,則不應顯示數據。或者你確定結束日期總是晚於開始日期?你打算創建一個列表日期列表嗎?然後它變得容易。否則,這並不容易。 –

回答

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行),它並不是一個很大的表格。 –

2

我想下面的查詢應該可以獲取結果。雖然我還沒有測試過這個查詢。

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://stackoverflow.com/questions/2157282/generate-days-from-date-range。以防萬一你需要。 –

+0

我得到這個錯誤'#1064 - 你的SQL語法有錯誤; (選擇curdate() - INTERVAL(aa +(10 * b'at line 2' – Chinmay235

+0

)對不起,對於您的MySQL服務器版本的手冊,選擇正確的語法來使用。我已經更正了現在的查詢。 –

相關問題