在SQL中查找具有时间间隔重叠的行的简单有效的方法是什么?
时间:2020-03-06 14:34:08 来源:igfitidea点击:
我有两个表,都包含开始时间和结束时间字段。我需要为第一个表中的每一行找到时间间隔相交的第二个表中的所有行。
例如:
<-----row 1 interval-------> <---find this--> <--and this--> <--and this-->
请以SQL" WHERE"子句的形式表达答案,并考虑第二个表中的结束时间可能为" NULL"的情况。
目标平台是SQL Server 2005,但其他平台的解决方案也可能会受到关注。
解决方案
SELECT * FROM table1,table2 WHERE table2.start <= table1.end AND (table2.end IS NULL OR table2.end >= table1.start)
select * from table_1 right join table_2 on ( table_1.start between table_2.start and table_2.[end] or table_1.[end] between table_2.start and table_2.[end] or (table_1.[end] > table_2.start and table_2.[end] is null) )
编辑:好的,不要寻求我的解决方案,它像狗屎一样蠕动。 " where"解决方案的速度提高了14倍。糟糕...
一些统计信息:在具有表1和表2的〜65000条记录的数据库上运行(无索引),每行的开始和结束之间有2天的间隔,在SQLSMSE中运行2分钟(没有耐心等待)
使用连接:2分钟内8356行
使用位置:2分钟内115436行