簡體   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