查找重叠日期给出无限循环MySQL

时间:2015-04-20 00:30:26

标签: mysql date

假设我有一个给定日期的表:

+-----------+-----------+----+
|StartDate  |EndDate    |ID  |
+-----------+-----------+----+
|2013-08-29 |2014-12-29 |1   |
|2013-08-29 |2013-09-31 |2   |
|2015-01-02 |2015-03-20 |3   |
+-----------+-----------+----+

我想找到冲突的日期,所以代码应该给我1作为冲突的日期。当我在MySQL中编写这段代码时,它会进入一个无限循环,我会感激一点帮助,因为我不明白为什么它不起作用:

select t1.* from dates t1
inner join dates t2
on t2.StartDate > t1.StartDate
and t2.StartDate < t1.EndDate;

谢谢。

2 个答案:

答案 0 :(得分:1)

不应该吗?:

select t1.*, t2.id as conflict_id
from dates t1
inner join dates t2
on t2.StartDate >= t1.StartDate
and t2.EndDate <= t1.EndDate
and t2.id != t1.id

答案 1 :(得分:0)

它不会进入无限循环。这需要很长很长时间。但是,这可能是一条更好的路线:

select d.*
from dates d
where exists (select 1
              from dates d2
              where d2.StartDate < d1.EndDate and
                    d2.EndDate > d1.StartDate
             );

dates(StartDate, EndDate)上的索引可能有助于查询。