在 MySQL 中,如何根据对同一个表执行 INNER JOIN 的表的结果执行 DELETE?
这基本上是我想要做的:
delete from course_plan_relationships
where course_plan_relationships.id not in (
select course_plan_relationships.id
from daily_plans inner join
course_plan_relationships on daily_plans.id=course_plan_relationships.daily_plan_id
);
为了让您了解发生的情况,我将向您展示子查询及其结果:
mysql> select course_plan_relationships.id from daily_plans inner join
course_plan_relationships on daily_plans.id=course_plan_relationships.daily_plan_id;
+----+
| id |
+----+
| 1 |
| 13 |
+----+
所以基本上,我想删除 course_plan_relationships 中的所有项目,其中它的 id 字段不在该表中我在子查询中生成了。
我得到的错误是:
错误 1093 (HY000):您无法指定目标表 'course_plan_relationships' 用于 FROM 子句中的更新
我基本上得到的是,出于某种原因,MySQL 不允许您基于涉及同一表的子查询进行 DELETE 或 UPDATE。
没关系,这是一个假设的解决方法: http ://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/
但它用于更新并且不使用“在”语法中。
我没有使用“AS blahothertablename”类型的语法(不断出现语法错误),而且我也无法弄清楚如何将初始子查询存储为临时结果(同样,语法错误)。
Here is basically what I want to do:
delete from course_plan_relationships
where course_plan_relationships.id not in (
select course_plan_relationships.id
from daily_plans inner join
course_plan_relationships on daily_plans.id=course_plan_relationships.daily_plan_id
);
To give you an idea of what's happening, I'll show you the subquery and its result:
mysql> select course_plan_relationships.id from daily_plans inner join
course_plan_relationships on daily_plans.id=course_plan_relationships.daily_plan_id;
+----+
| id |
+----+
| 1 |
| 13 |
+----+
So basically, I want to delete all items in course_plan_relationships, where its id field is not in that table I generated there in the subquery.
The error I get is:
ERROR 1093 (HY000): You can't specify target table
'course_plan_relationships' for update in FROM clause
What I've basically gotten is that for some reason MySQL won't let you DELETE or UPDATE based on a sub-query involving the same table.
That's fine, and here's a supposed workaround:
http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/
But its for UPDATE and doesn't use the "in" syntax.
I haven't had any luck using the "AS blahothertablename" kind of syntax (keep getting syntax errors), and I also can't figure out how to store the initial subquery as a temporary result (again, syntax errors).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在删除中使用多表语法,不需要子查询:
http://dev.mysql.com/doc/refman/5.0/en/delete.html
Using multi-table syntax in the delete, you don't need the sub-query:
http://dev.mysql.com/doc/refman/5.0/en/delete.html
根据您的解决方法,类似这样的事情应该有效:
According to your workaround, something like this should work:
我认为这相当于你想要的(假设
course_plan_relationships.id
是表的主键):I think this is equivalent to what you want (assuming that
course_plan_relationships.id
is the primary key of the table):