如果关联的Join条目不存在,请删除记录

时间:2017-07-10 08:38:07

标签: postgresql postgresql-9.4

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

相关表格为merchantsmerchant_configurations

merchant_configurations对商家表foreign key id

primary key merchant_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子句和内容

2 个答案:

答案 0 :(得分:1)

使用NOT EXISTS,简单而有效:

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

答案 1 :(得分:1)

您还可以使用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