SQL一对多关系

问题描述

我正在尝试找出仅列出一对多关系的SQL查询

下面的表包含11条记录,其中我想返回Field1 = 7(一对多)的两行

表1:

Field1  Field2  
1   a   
2   a   
3   b   
4   b   
5   c   
4   d   exclude 4 and 6 as d is linked to both

6   d   
6   e   
7   f   One to Many
7   j   One to Many
8   g   

enter image description here

解决方法

您希望所有field2的所有field1值都出现一次。这是使用窗口函数的方法:

select field1
from (select t.*,count(*) over (partition by field2) as num_field2
      from t
     ) t
group by field1
having count(*) > 1 and max(num_field2) = 1;