给出一个具有双向对的表,即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 |
+----------+------------+
答案 0 :(得分:2)
一种方法是:
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;
答案 1 :(得分:1)
一种方法是使用具有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
)