【问题标题】:PostgreSQL delete rows that outer join from multiple tablesPostgreSQL 从多个表中删除外部连接的行
【发布时间】:2021-07-05 20:37:03
【问题描述】:

我正在尝试从其他 2 个故事中不存在其 ID 的表中删除行。在 PostgreSQL 上:

表 A:

idB idC age
1 4 Three
2 5 Three
3 6 Three

表 B:

idB name age
3 Two Three
7 Two Three

表 C:

idC name age
4 Two Three
5 Two Three
6 Two Three

决赛桌A:

idB idC age
3 6 Three

应该删除表 A 的第一行,因为表 C 中不存在 idC = 4 应该删除表 A 的第二行,因为表 B 中不存在 idB = 2 表A的第三行应该保持idB = 3存在于表B中,idC = 6存在于表C中

我该怎么做?

【问题讨论】:

    标签: sql postgresql join sql-delete outer-join


    【解决方案1】:

    只需使用not exists:

    delete from tableA a
        where not exists (select 1 from tableB b where b.idB = a.idB) or
              not exists (select 1 from tableC c where c.idC = a.idC);
    

    【讨论】:

      【解决方案2】:

      你可以这样做:

      with tt as (
        select a.* from tableA a
        left join tableB b on a.idb =b.idb
        left join tableC c on a.idC = c.idc
        where b.idb is null or c.idc is null
      )
      delete from tableA a
      using tt 
      where a.idB = tt.idB
      and a.idC = tt.idC
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-02-15
        • 1970-01-01
        • 1970-01-01
        • 2015-05-02
        • 2012-07-30
        • 1970-01-01
        • 2011-10-16
        • 1970-01-01
        相关资源
        最近更新 更多