MySQL - 当嵌套选择使用该表时如何从表中删除?

发布于 2024-11-08 02:19:43 字数 448 浏览 0 评论 0原文

我正在尝试做这样的事情:

DELETE FROM table_1
WHERE  table_1.id IN (SELECT table_1.id
                      FROM   table_1,
                             table_2,
                             table_3
                      WHERE  table_1.id = table_2.table_1_id
                      AND    table_2.id = table_3.table_2_id
                      AND    table_3.id = 5) 

似乎 MySQL 不允许我在嵌套 SELECT 中拥有 table_1 。建议?

I'm trying to do something like this:

DELETE FROM table_1
WHERE  table_1.id IN (SELECT table_1.id
                      FROM   table_1,
                             table_2,
                             table_3
                      WHERE  table_1.id = table_2.table_1_id
                      AND    table_2.id = table_3.table_2_id
                      AND    table_3.id = 5) 

Seems like MySQL won't let me have table_1 in the nested SELECT. Suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

小帐篷 2024-11-15 02:19:43

您可能会收到此错误:

ERROR 1093 (HY000): You can't specify target table 'table_1' for update in FROM clause.

您应该能够使用 MySQL 的多表 DELETE 语法:

DELETE table_1.*
FROM   table_1,
       table_2,
       table_3
WHERE  table_1.id = table_2.table_1_id
AND    table_2.id = table_3.table_2_id
AND    table_3.id = 5

上面的查询应该可以工作,但作为一般规则,我建议使用 ANSI JOIN 语法:

DELETE table_1.*
FROM   table_1
INNER JOIN table_2 on table_2.table_1_id = table_1.id
INNER JOIN table_3 on table_3.table_2_id = table_2.id
WHERE table_3.id = 5

You're probably getting this error:

ERROR 1093 (HY000): You can't specify target table 'table_1' for update in FROM clause.

You should be able to do this using MySQL's multiple-table DELETE syntax instead:

DELETE table_1.*
FROM   table_1,
       table_2,
       table_3
WHERE  table_1.id = table_2.table_1_id
AND    table_2.id = table_3.table_2_id
AND    table_3.id = 5

The above query should work, but as a general rule I would recommend using ANSI JOIN syntax instead:

DELETE table_1.*
FROM   table_1
INNER JOIN table_2 on table_2.table_1_id = table_1.id
INNER JOIN table_3 on table_3.table_2_id = table_2.id
WHERE table_3.id = 5
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文