在SQL中查找具有时间间隔重叠的行的简单有效方法是什么?

Ste*_*owe 29 sql

我有两个表,都有开始时间和结束时间字段.我需要为第一个表中的每一行找到第二个表中时间间隔相交的所有行.

例如:

           <-----row 1 interval------->
<---find this--> <--and this--> <--and this-->
Run Code Online (Sandbox Code Playgroud)

请以SQL- WHEREclause 的形式表达您的答案,并考虑第二个表中的结束时间可能的情况NULL.

目标平台是SQL Server 2005,但其他平台的解决方案也可能是有意义的.

Kho*_*oth 55

SELECT * 
FROM table1,table2 
WHERE table2.start <= table1.end 
AND (table2.end IS NULL OR table2.end >= table1.start)
Run Code Online (Sandbox Code Playgroud)

  • 证明:如果两个间隔不重叠则(s2> e1 || e2 <s1).如果它们重叠,则反转条件:(!(s2> e1 || e2 <s1)).现在可以使用!(a || b)=!a &&!b进行简化.因此(s2 <= e1 && e2> = s1). (9认同)