我正在尝试找出SQL查询,该查询将从下表中仅列出一对一的关系。
下表包含10条记录,其中8条多对多关系数据和2条一对一关系。请求您提供有关SQL的帮助,我可以用来查询下表,并列出2个具有一对一关系的记录。 注意:表支持多对多关系。
表1:
Field1 Field2
1 a
2 a
3 b
4 b
5 c One to One
4 d
6 d
6 e
7 f
7 j
8 g One to One
答案 0 :(得分:0)
您可以使用窗口功能:
select t.*
from (select t.*, count(*) over (partition by field1) as cnt1,
count(*) over (partition by field2) as cnt2
from t
) t
where cnt1 = 1 and cnt2 = 1;
您也可以使用not exists
:
select t.*
from t
where not exists (select 1
from t t2
where t2.field1 = t.field1 and t2.field2 <> t.field2
) and
not exists (select 1
from t t2
where t2.field2 = t.field2 and t2.field1 <> t.field1
) ;