未经测试,我相信下面会给你正确的答案,没有重复(把戏删除重复是确保t1.DEFF < = t2.DEFF总是):
SELECT t1.ID,
t1.DEFF AS DEFF1, t1.DEND AS DEND1
t2.DEFF AS DEFF2, t2.DEND AS DEND2
FROM table1 t1
-- exclude yourself in join (assuming that no two entries are identical)
INNER JOIN table1 t2 ON t1.ID = t2.ID
AND t1.DEFF <= t2.DEFF
AND t1.DEFF != t2.DEFF
AND t1.DEND != t2.DEND
WHERE
-- check for overlap including t1 fully inside of t2
(t1.DEFF BETWEEN t2.DEFF AND t2.DEND
OR t1.DEND BETWEEN t2.DEFF AND t2.DEND)
OR
-- needed to additionally catch t2 fully inside of t1
(t2.DEFF BETWEEN t1.DEFF AND t1.DEND
OR t2.DEND BETWEEN t1.DEFF AND t1.DEND)
更新:认识到我的JOIN限制,其中t1.DEFF < = t2.DEFF意味着t1永远不会在t2内。 Where子句然后可以简化为单一的检查(例如,确保T2不启动T1结束前):
SELECT t1.ID,
t1.DEFF AS DEFF1, t1.DEND AS DEND1
t2.DEFF AS DEFF2, t2.DEND AS DEND2
FROM table1 t1
-- exclude yourself in join (assuming that no two entries are identical)
INNER JOIN table1 t2 ON t1.ID = t2.ID
AND t1.DEFF <= t2.DEFF
AND t1.DEFF != t2.DEFF
AND t1.DEND != t2.DEND
WHERE
t2.DEFF <= t1.DEND
我的理解是,你会想在t2.ID = t1.ID上做这样的连接,因为根据以下问题,ID不是唯一的:“获取具有重叠的相同ID的记录” –
编辑的查询现在有很多误报......它也会有重复。现在有一个新的编辑:) –
很确定这不是必要的'AND t2.DEND> = t1.DEFF' –