2011-12-19 99 views
0

我正在處理事件callendar,並且無法找到在給定範圍內選擇我的事件的mysql查詢。我的活動有開始/結束日期,所以我的範圍(月)。php mysql雙日期範圍

我已經盡了全力去描繪我所期待的(我想選擇事件1,2,3,4而不是5或6)

  |========= April ===========|   => Range 
    +--(1)--+     +--(2)--+  => Partialy Overlapping Events 
        +--(3)--+      => Events included in range 
    +----------------(4)----------------+  => Ovelapping events 
+-(5)-+         +-(6)-+ => Events outside of range 

我發現這個類似quastion: 2 Column Mysql Date Range Search in PHP但我不認爲這是重複的,因爲如果我在我的問題中正確理解範圍有開始和結束日期,而在另一個問題範圍是單一日期。

+0

您的範圍如何給出,事件表的表格模式是什麼? – codeling 2011-12-19 10:05:58

回答

5

該解決方案與您鏈接的問題仍然非常相似;嘗試此查詢:

SELECT * FROM events e 
    WHERE `start` <= [RANGE.end] 
    AND `end` >= [RANGE.start] 

你當然必須更換[RANGE.start]和[RANGE.end]你的範圍的第一個和最後日期。如果例如RANGE.start ='2011-04-01'和RANGE.end ='2011-04-30',上述查詢將給出'11年4月發生的所有結果。

根據您是否要選擇事件,只是「觸摸」的範圍內(這意味着他們有一個共同的邊界日期,但實際上並不重疊),您都可以通過</>更換<=/>=

+0

我現在看到,非常有意義 – Purplefish32 2011-12-19 10:17:15

+0

我試圖讓這個非常大的查詢和你節省了我很多時間,謝謝。 – 2014-07-25 13:16:33

3

給這個去吧。我編寫了一個名爲dateRangeExample的表來說明答案:

drop table if exists dateRangeExample; 

create table dateRangeExample 
(id int unsigned primary key, 
startDate date not null, 
endDate date not null 
); 


insert into dateRangeExample (id,startDate,endDate) values (1,'2011-03-15','2011-04-05'); 
insert into dateRangeExample (id,startDate,endDate) values (2,'2011-04-25','2011-05-05'); 
insert into dateRangeExample (id,startDate,endDate) values (3,'2011-04-10','2011-04-15'); 
insert into dateRangeExample (id,startDate,endDate) values (4,'2011-03-15','2011-05-05'); 
insert into dateRangeExample (id,startDate,endDate) values (5,'2011-03-01','2011-03-20'); 
insert into dateRangeExample (id,startDate,endDate) values (6,'2011-05-03','2011-05-25'); 

select dre.* 
from dateRangeExample dre 
where startDate between '2011-04-01' and '2011-04-30' 
or endDate between '2011-04-01' and '2011-04-30' 
or (startDate < '2011-04-01' and endDate > '2011-04-30');