我正在尝试找出SQL查询,它将只列出下表中的一对一关系。
下表包含10条记录,其中8条是多对多关系数据,2条是一对一关系。请求您的帮助与SQL,我可以用来查询下表,并列出2个记录,具有一对一的关系。注意:表支持多对多关系。
Table1:
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发布于 2020-09-09 23:59:04
您可以使用窗口函数:
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
) ;https://stackoverflow.com/questions/63815294
复制相似问题