我正在编写一个SQL查询以从表中获取结果。
这是一个实际的问题:在我的数据库中,有一个名为Contact
的表。
该表中有两列Calling_Person
和Called_Person
。
假定该表包含以下数据:
表格:Contact
Calling_Person Called_Person
--------------------------------------
AB CD
CD AB
AB EF
EF AB
AB PQ
PQ XY
XY UV
XY ZW
UV XY
从上表中,我们只需要互相打电话的人。
预期输出:
Calling_Person Called_Person
--------------------------------------
AB CD
AB EF
XY UV
在上表中,
我写了以下查询,但结果如下:
select *
from test
where id2 in (select id1 from test as t
where id2 in (select id1 from test where id1 = t.id2)
)
结果:
Calling_Person Called_Person
--------------------------------------
AB CD
CD AB
AB EF
EF AB
XY UV
UV XY
答案 0 :(得分:1)
我猜您正在尝试将相同的对(例如(a,b)
和(b,a)
)组合在一起。您需要使用条件id1 < id2
将其中一行标记为“主”行,并检查是否存在匹配项:
SELECT *
FROM t AS t1
WHERE id1 < id2 AND EXISTS (
SELECT 1
FROM t AS t2
WHERE t2.id1 = t1.id2 AND t2.id2 = t1.id1
)
答案 1 :(得分:0)
如果您有所有配对,则只需使用:
select t.*
from t
where id1 < id2;
如果您有一对,那么:
select t.*
from t
where id1 < id2 or
not exists (select 1
from t t2
where t2.id1 = t.id2 and t2.id2 = t.id1
);
如果您实际上有重复项,请使用select distinct
:
select distinct id1, id2
from t
where id1 < id2 or
not exists (select 1
from t t2
where t2.id1 = t.id2 and t2.id2 = t.id1
);