繁体   English   中英

在 MySQL 中,如何根据我对同一张表进行 INNER JOIN 的表的结果进行删除?

[英]In MySQL, how can I do a DELETE based on the result from a table where I did an INNER JOIN with the same table?

好的,所以我确实很讨厌 MySQL,但这基本上是我想做的:

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 字段不在我在子查询中生成的那个表中。

我得到的错误是:

ERROR 1093 (HY000): 您不能在 FROM 子句中指定目标表 'course_plan_relationships' 进行更新

我基本上得到的是,由于某种原因,MySQL 不会让您基于涉及同一个表的子查询进行删除或更新。

没关系,这是一个假定的解决方法: http://www.xaprb.com/blog/2006/06/23/how-to-select-from-an-update-target-in-mysql/

但它用于 UPDATE 并且不使用“in”语法。

我对这些东西真的很陌生,所以任何帮助都会非常感激。 我没有任何运气使用“AS blahothertablename”类型的语法(不断收到语法错误),而且我也无法弄清楚如何将初始子查询存储为临时结果(再次,语法错误)。

在删除中使用多表语法,不需要子查询:

DELETE course_plan_relationships
FROM course_plan_relationships LEFT JOIN
daily_plans ON course_plan_relationships.daily_plan_id = daily_plans.id
WHERE daily_plans.id IS NULL;

http://dev.mysql.com/doc/refman/5.0/en/delete.html

根据您的解决方法,这样的事情应该可以工作:

delete from course_plan_relationships where course_plan_relationships.id not in 
(
  select x.id from 
   (
     select course_plan_relationships.id from daily_plans 
     inner join course_plan_relationships
     on daily_plans.id=course_plan_relationships.daily_plan_id
   ) AS x
) 

我认为这相当于你想要的(假设course_plan_relationships.id是表的主键):

DELETE FROM course_plan_relationships AS cpr
WHERE NOT EXISTS
    ( SELECT *
      FROM daily_plans AS dp 
      WHERE dp.id = cpr.daily_plan_id
    ) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM