2011-12-19 98 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');