我有一个表,每行存储一个开始日期/时间和结束日期/时间的会议.
meetingID int
meetingStart datetime
meetingEnd datetime
期望的输出:对于每对重叠的行,我想输出
meetingID,meetingStart,meetingID,meetingEnd
在MySQL中执行此类查询的最有效方法是什么?
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
这将选择每对两次.
如果您只想选择一对,请使用:
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
请确保您有索引meetingStart
和meetingEnd
用于查询高效地工作.
MySQL
但是,可能会INDEX MERGE
用来运行此查询,这在当前实现中效率不高.
您也可以尝试使用:
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
,这更复杂,但最有可能运行得更快一点.