两个表 - 如果两个表中均未引用 ID,如何删除行
我有两个表:
listings(item_id, ...)
images(item_id, ...)
两个表中的 item_id 值相同 - 但我从“listings”表中删除了列表,而没有删除“images”表中的相应行。
因此 - 如果 IMAGES 中的 item_id 与我的主“listings”表中的任何更新的 item_id 值不对应,我想删除第二个“images”表中的所有行。
如何删除“images”表中未从“listings”引用的所有记录?
我一直在尝试像这样的 SQL 脚本和子查询:
DELETE FROM images WHERE item_id IN
(SELECT item_id FROM images EXCEPT SELECT item_id FROM listings)
但在我搞砸一切之前,想确认这是否正确?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该使用子查询
更多示例和说明。
You should use a sub query
More examples and explanation.
这里有一个处理这些微妙情况的好技巧:
在运行一个如果写得不正确可能会造成重大损害的查询之前,用 SELECT 替换 DELETE/UPDATE 以查看查询将影响哪些行。在你的情况下,它会是:
当然,你也想在发出这样的命令之前通过备份数据库来掩盖自己。即使您的查询在 SELECT 测试中看起来是正确的,您也永远不知道......
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:
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...
这可以工作,或者
IN
子句也可以。That would work, or the
IN
clause as well.对我来说更清楚地说
To me it'd be clearer to say