What is a simple and efficient way to find rows with time-interval overlaps in SQL?

后端 未结 5 1558
清歌不尽
清歌不尽 2020-11-30 00:22

I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals in

5条回答
  •  醉话见心
    2020-11-30 00:29

    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)
    )
    

    EDIT: Ok, don't go for my solution, it perfoms like shit. The "where" solution is 14x faster. Oops...

    Some statistics: running on a db with ~ 65000 records for both table 1 and 2 (no indexing), having intervals of 2 days between start and end for each row, running for 2 minutes in SQLSMSE (don't have the patience to wait)

    Using join: 8356 rows in 2 minutes

    Using where: 115436 rows in 2 minutes

提交回复
热议问题