当前位置:  开发笔记 > 后端 > 正文

在一个表中查找重叠(日期/时间)行

如何解决《在一个表中查找重叠(日期/时间)行》经验,为你挑选了1个好方法。

我有一个表,每行存储一个开始日期/时间和结束日期/时间的会议.

meetingID int
meetingStart datetime
meetingEnd datetime

期望的输出:对于每对重叠的行,我想输出
meetingID,meetingStart,meetingID,meetingEnd

在MySQL中执行此类查询的最有效方法是什么?



1> Quassnoi..:
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

请确保您有索引meetingStartmeetingEnd用于查询高效地工作.

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

,这更复杂,但最有可能运行得更快一点.

推荐阅读
携手相约幸福
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有