[英]Overlapping date range MySQL
我有以下数据;
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。
选择重叠的查询(不过,我将列名startTime和endTime命名为,因为Time似乎很重要...):
WHERE
<start> < endDate
AND
<end> > startDate
这可能不是最好的方法,但是也许您可以从此示例中看到一些东西。 仅当它们重叠时,这才返回结果,并且我可能会在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的回答,您可能还需要检查这些值是否也不完全匹配。
重叠条目:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.