Find overlapping (date/time) rows within one table

后端 未结 4 1411
广开言路
广开言路 2021-01-30 12:13

I have a table which stores in each row a meeting with start date/time and end date/time.

meetingID int
meetingStart datetime
meetingEnd datetime

De

4条回答
  •  臣服心动
    2021-01-30 12:19

    Adding both meetings' start and end times to the result rows:

    SELECT m1.meetingID AS firstID, m1.meetingStart AS firstStart, 
    m1.meetingEnd AS firstEnd, m2.meetingID AS secondID, 
    m2.meetingStart AS secondStart, m2.meetingEnd AS secondEnd 
    FROM meeting AS m1, meeting AS m2 
    WHERE (m2.meetingStart BETWEEN m1.meetingStart AND m1.meetingEnd) 
    AND (m1.meetingID != m2.meetingID)
    

    This way m2 will always be the one starting at the same time or after m1, and m1.id!=m2.id ensures that it will not contain matches against itself.

    You don't need to check against the meeting end, as the overlap can be reliably detected from just comparing the meeting start.

提交回复
热议问题