来自双向对的sql唯一对

63lcw9qa  于 2021-06-25  发布在  Hive
关注(0)|答案(2)|浏览(367)

给定一个具有双向对的表,即a和b,b和a:

+-----------------------+
| Person_1 |   Person_2 |
+----------+------------+
| Nancy    |   John     |
| Nancy    |   Mary     |   
| John     |   Nancy    |
| Peter    |   Jane     |
| Jane     |   Peter    |
+----------+------------+

如何在任何方向上仅选择唯一对,例如:

+-----------------------+
| Person_1 |   Person_2 |
+----------+------------+
| Nancy    |   John     |
| Nancy    |   Mary     |
| Peter    |   Jane     |   
+----------+------------+
n9vozmp4

n9vozmp41#

一种方法是:

select person_1, person_2
from t
where person_1 < person_2
union al
select person_1, person_2
from t
where person_1 > person_2 and
      not exists (select 1 from t t2 where t2.person_1 = t.person_2 and t2.person_2 = t.person_1);

这保留了对的原始顺序——因此返回的行在源数据中。如果这不重要:

select distinct least(person_1, person_2), greatest(person_1, person_2)
from t;
5cnsuln7

5cnsuln72#

一种方法是使用具有 exists 条件:

select *
from mytable t
where 
    t1.person_1 < t.person_2 
    and exists (
        select 1
        from mytable t1
        where t1.person_1 = t.person_2 and t1.person_2 = t.person_1
)

相关问题