Delete a record if the associated Join entry does not exist

江枫思渺然 提交于 2019-12-13 07:26:20

问题


I'm trying to delete a record from a table if the parent table record does not exist.

The table in question are merchants and merchant_configurations

merchant_configurations has a foreign key(merchant_id) reference to merchant table primary key (id)

Here how the 2 tables looks

== merchant_configurations
  id           integer
  merchant_id  integer
  config_options  hstore

Merchant table

== merchants
  id integer
  name string

Now, select query to retrieve all those merchant_configurations record for whose merchant record is delete look like this

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

Now, I essentially want is to delete all those record but for some reason

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 

Does not seem to work.

The only way I manage to get it done using WITH clause.

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);

Now my question is:

Is it possible to delete the Record using normal way without having to do the WITH clause and stuff


回答1:


Use NOT EXISTS, it is simple and efficient:

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



回答2:


You can also use 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


来源:https://stackoverflow.com/questions/45007359/delete-a-record-if-the-associated-join-entry-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!