Two tables - how to delete rows if ID not referenced in both tables

杀马特。学长 韩版系。学妹 提交于 2019-12-12 14:27:56

问题


I have two tables:

listings(item_id, ...)
images(item_id,  ...)

The item_id value is the same in both tables - but I goofed and deleted listings from the 'listings' table without also deleting the corresponding row in the 'images' table.

So - I want to delete all rows in the second 'images' table if item_id in IMAGES doesn't correspond to any of the more up-to-date item_id values in my primary 'listings' table.

How do you delete all records in the 'images' table that are not referenced from 'listings'?

I've been experimenting with a SQL script and sub-query like this:

DELETE FROM images WHERE item_id IN
(SELECT item_id FROM images EXCEPT SELECT item_id FROM listings)

But before I screw it all up, want to confirm if this is correct?


回答1:


You should use a sub query

DELETE FROM images WHERE item_id NOT IN(SELECT item_id FROM listings)

More examples and explanation.




回答2:


Here's a nice trick for dealing with these delicate situations:

Before you run a query which may cause significant harm if not written right, replace the DELETE/UPDATE with a SELECT to see which rows your query will affect. In your case, it would be:

SELECT * 
-- DELETE
FROM images WHERE item_id NOT IN (SELECT item_id FROM listings) 

Of course, you also want to cover yourself by backing up the db before issuing such a command. Even when your query looks correct with the SELECT test, you never know...




回答3:


That would work, or the IN clause as well.

DELETE
FROM image
WHERE item_id NOT IN (SELECT item_id FROM listings)



回答4:


To me it'd be clearer to say

DELETE FROM images WHERE item_id NOT IN 
    (SELECT item_id FROM listings) 


来源:https://stackoverflow.com/questions/5835589/two-tables-how-to-delete-rows-if-id-not-referenced-in-both-tables

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