重叠日期范围MySQL

时间:2010-09-08 12:24:22

标签: php mysql datetime

我有以下数据;

ID  startDate               endDate
-----------------------------------------------
1   2010-03-01 10:00:00     2010-03-01 12:00:00
2   2010-03-01 12:30:00     2010-03-01 15:30:00
3   2010-03-01 15:30:00     2010-03-01 18:30:00

我想要做的是检查开始日期和结束日期是否属于我的数据中的startDate和endDate范围。

例如,以下情况可以;

startDate               endDate
-----------------------------------------------
2010-03-01 12:00:00     2010-03-01 12:30:00
2010-03-01 18:30:00     2010-03-01 21:00:00

但是以下日期会失败,因为它们会重叠;

startDate               endDate
-----------------------------------------------
2010-03-01 09:00:00     2010-03-01 13:00:00 (overlaps ID 1)
2010-03-01 10:30:00     2010-03-01 11:00:00 (overlaps ID 1)
2010-03-01 18:00:00     2010-03-01 19:00:00 (overlaps ID 3)

我正在拔头发,因为我可以让上述3个测试日期范围中的一个或两个失败,但不是全部。

我正在使用MySQL。

3 个答案:

答案 0 :(得分:7)

选择重叠的查询(我将列命名为startTime& endTime,因为时间似乎很重要......):

WHERE 
<start> < endDate
AND
<end> > startDate

答案 1 :(得分:0)

这可能不是最好的方法,但也许你可以从这个例子中汲取灵感。这只会在它们重叠时返回结果,我可能会在not exists查询中使用它。

select 1 from myTable
where 
('03/01/2010 09:00:00' between startDate and endDate)
or
('03/01/2010 13:00:00' between startDate and endDate)
or 
(startDate between '03/01/2010 09:00:00' and '03/01/2010 13:00:00')
or
(endDate between '03/01/2010 09:00:00' and '03/01/2010 13:00:00')

根据Wrikken的回答,您可能需要检查值是否也不完全匹配。

答案 2 :(得分:0)

重叠条目:

SELECT t1.Id, t2.Id, t1.StartDate, t1.EndDate, t2.StartDate, t2.EndDate
FROM Table t1, Table t2
WHERE t1.ID <> t2.Id
AND (t1.StartDate between t2.StartDate and t2.EndDate
    OR
     t1.EndDate between  t2.StartDate and t2.EndDate)
相关问题