一个表的SQL条件联合

时间:2018-12-01 04:08:24

标签: sql

我有一个看起来像这样的表:

tblUser

   id | name    | start_Date | end_date
    1 | anna    | 2018-01-01 | 2018-06-30
    2 | benzema | 2018-02-01 | 2018-05-30
    3 | bale    | 2018-02-14 | 2018-02-24
    4 | kroos   | 2019-03-14 | 2019-10-21

我想选择起始日期和结束日期重叠的名称,并返回与以下结果类似的结果,其中第一列是与值较低的id对应的名称:

     name1      | name2
   | anna       | benzema
   | anna       | bale
   | benzema    | bale

我看了条件联合答案here,但这并不完全正确,因为我使用的是单个表而不是两个表。使用两个不同的别名为tblUser设置条件联合是否正确?

2 个答案:

答案 0 :(得分:2)

一个简单的JOIN查询就足够了,当两个表之间的开始日期和结束日期重叠时,将tblUser与其自身相连:

SELECT t1.name AS name1, t2.name AS name2
FROM tblUser t1
JOIN tblUser t2 ON (t2.start_Date BETWEEN t1.start_Date and t1.end_date 
                OR t2.end_date BETWEEN t1.start_Date and t1.end_date)
                AND t2.id != t1.id
ORDER BY t1.id

输出:

name1       name2
anna        benzema
anna        bale
benzema     bale

Demo on SQLFiddle

答案 1 :(得分:0)

我相信正确的逻辑是:

SELECT u1.name AS name1, u2.name AS name2
FROM tblUser u1 JOIN
     tblUser u2
     ON u1.start_date < u2.end_date AND
        u1.end_date > u2.start_date AND
        u1.id < u2.id
ORDER BY u1.id;

一个周期在第二个结束之前开始,而第一个结束在第二个结束之后两个时期重叠。