两个表 - 如果两个表中均未引用 ID,如何删除行

发布于 2024-11-04 15:46:19 字数 476 浏览 6 评论 0原文

我有两个表:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一人独醉 2024-11-11 15:46:19

您应该使用子查询

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

更多示例和说明

You should use a sub query

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

More examples and explanation.

痴情换悲伤 2024-11-11 15:46:19

这里有一个处理这些微妙情况的好技巧:

在运行一个如果写得不正确可能会造成重大损害的查询之前,用 SELECT 替换 DELETE/UPDATE 以查看查询将影响哪些行。在你的情况下,它会是:

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

当然,你也想在发出这样的命令之前通过备份数据库来掩盖自己。即使您的查询在 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:

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...

香草可樂 2024-11-11 15:46:19

这可以工作,或者 IN 子句也可以。

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

That would work, or the IN clause as well.

DELETE
FROM image
WHERE item_id NOT IN (SELECT item_id FROM listings)
瞎闹 2024-11-11 15:46:19

对我来说更清楚地说

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

To me it'd be clearer to say

DELETE FROM images WHERE item_id NOT IN 
    (SELECT item_id FROM listings) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文