SQL Select 显示一对一,一对多,多对多的关系

SQL Select to display one to one, one to many from many to many relation

我正在尝试找出 SQL 查询,该查询将仅列出下面的一对一关系 table。

下面Table包含10条记录,其中8条是多对多关系数据,2条是一对一关系。请求您帮助 SQL,我可以使用它在 table 下方查询并列出具有一对一关系的 2 条记录。 注意:Table支持多对多关系。

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

enter image description here

您可以使用 window 函数:

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
                 ) ;