【问题标题】:Delete a record if the associated Join entry does not exist如果关联的 Join 条目不存在,则删除记录
【发布时间】:2017-07-10 08:38:07
【问题描述】:

如果父表记录不存在,我正在尝试从表中删除记录。

有问题的表是merchantsmerchant_configurations

merchant_configurations 有一个 foreign key(merchant_id) 引用商人表 primary key (id)

这两张桌子的样子

== merchant_configurations
  id           integer
  merchant_id  integer
  config_options  hstore

商户表

== merchants
  id integer
  name string

现在,选择查询以检索其商户记录被删除的所有商家配置记录,如下所示

select merchant_configurations.id from merchant_configurations LEFT JOIN merchants ON merchant_configurations.merchant_id = merchants.id where merchants.id IS NULL

现在,我基本上想要删除所有这些记录,但出于某种原因

DELETE merchants_configurations from select merchant_configurations.id from merchant_configurations LEFT JOIN merchants ON merchant_configurations.merchant_id = merchants.id where merchants.id IS NULL 

似乎不起作用。

我设法使用 WITH 子句完成它的唯一方法。

WITH zombie_configurations AS (
   select merchant_configurations.id from merchant_configurations LEFT JOIN 
   merchants ON merchant_configurations.merchant_id = merchants.id where 
   merchants.id IS NULL 
)

DELETE from merchant_configurations where id IN (select id from zombie_configurations);

现在我的问题是:

是否可以使用正常方式删除记录而无需执行WITH 子句和其他内容

【问题讨论】:

    标签: postgresql postgresql-9.4


    【解决方案1】:

    使用NOT EXISTS,简单高效:

    SELECT FROM merchant_configurations mc
    WHERE NOT EXISTS (SELECT 1
                      FROM merchants m
                      WHERE mc.merchant_id = m.id);
    

    【讨论】:

      【解决方案2】:

      你也可以使用USING:

      DELETE FROM merchant_configurations AS mc
      USING merchant_configurations AS mc2
      LEFT JOIN merchants ON mc2.merchant_id = merchants.id
      WHERE mc2.id = mc.id AND merchants.id IS NULL
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-23
        • 2014-06-17
        • 2015-09-26
        • 2015-03-04
        相关资源
        最近更新 更多