【问题标题】:How do you select foreign key rows that do not exist in the parent table in Postgres?如何在 Postgres 中选择父表中不存在的外键行?
【发布时间】:2020-01-08 02:37:04
【问题描述】:

表2:

id (pk)
table1_id (fk)
other_columns

表1:

id (pk)
other_columns

表 1 记录已被删除,但表 2 引用仍然存在并且未被取消。您如何最好地从表 2 中查询选择表 1 中不存在的外键的列表?

【问题讨论】:

    标签: sql postgresql select foreign-keys


    【解决方案1】:

    你可以使用not exists:

    select t2.*
    from table2 t2
    where not exists (select 1 from table1 t1 where t1.id = t2.table1_id)
    

    您可以轻松地将其转换为delete 声明:

    delete from table 2
    where not exists (select 1 from mytable where t1.id = t2.table1_id)
    

    【讨论】:

      【解决方案2】:

      如果您有级联外键约束,这将不是问题。但是你可以使用not exists:

      select t2.*
      from table2 t2
      where not exists (select 1
                        from table1 t1
                        where t1.pk = t2.fk
                       );
      

      【讨论】:

        猜你喜欢
        • 2018-03-10
        • 2015-03-30
        • 1970-01-01
        • 2018-02-28
        • 2015-05-06
        • 2011-10-07
        • 2012-08-10
        • 2013-12-29
        • 2016-09-18
        相关资源
        最近更新 更多