SELECT m1.meetingID, m1.meetingStart, m1.meetingEnd, m2.meetingID
FROM t_meeting m1, t_meeting m2
WHERE (m2.meetingStart BETWEEN m1.meetingStart AND m1.meetingEnd
OR m2.meetingEnd BETWEEN m1.meetingStart AND m1.meetingEnd)
AND m1.meetingID <> m2.meetingID
This will select each pair twice.
If you want each pair to be selected just once, use:
SELECT m1.meetingID, m1.meetingStart, m1.meetingEnd, m2.meetingID
FROM t_meeting m1, t_meeting m2
WHERE (m2.meetingStart BETWEEN m1.meetingStart AND m1.meetingEnd
OR m2.meetingEnd BETWEEN m1.meetingStart AND m1.meetingEnd)
AND m2.meetingID > m1.meetingID
Make sure you have indexes on meetingStart
and meetingEnd
for the query to work efficiently.
MySQL
, however, will probably use INDEX MERGE
to run this query, which is not very efficient in current implementation.
You also may try to use:
SELECT m1.*, m2.*
FROM (
SELECT m1.meetingID AS mid1, m2.meetingID AS mid2
FROM t_meeting m1, t_meeting m2
WHERE m2.meetingStart BETWEEN m1.meetingStart AND m1.meetingEnd
AND m2.meetingID <> m1.meetingID
UNION
SELECT m1.meetingID, m2.meetingID
FROM t_meeting m1, t_meeting m2
WHERE m2.meetingEnd BETWEEN m1.meetingStart AND m1.meetingEnd
AND m2.meetingID <> m1.meetingID
) mo, t_meeting m1, t_meeting m2
WHERE m1.meetingID = mid1
AND m2.meetingID = mid2
, which is more complex but will most probably run a little bit faster.