【问题标题】:SQL one to many from many to many relationSQL 一对多从多对多的关系
【发布时间】:2020-09-10 02:26:03
【问题描述】:

我正在尝试找出只列出一对多关系的 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   

【问题讨论】:

    标签: sql one-to-many


    【解决方案1】:

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

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-05
      • 1970-01-01
      • 2018-06-15
      • 2015-09-20
      • 2020-09-15
      相关资源
      最近更新 更多