小编典典

SQL DELETE与JOIN另一个表在WHERE条件

mysql

我必须从中删除guide_categoryguide表无关的行(无效关系)。

这是我想做的,但是它当然不起作用。

DELETE FROM guide_category AS pgc 
 WHERE pgc.id_guide_category IN (SELECT id_guide_category 
                                   FROM guide_category AS gc
                              LEFT JOIN guide AS g ON g.id_guide = gc.id_guide
                                  WHERE g.title IS NULL)

错误:

您不能在FROM子句中指定目标表’guide_category’进行更新


阅读 805

收藏
2020-05-17

共1个答案

小编典典

由于锁定实现问题,MySQL不允许使用DELETE或引用受影响的表UPDATE

您需要在JOIN此处制作一个:

DELETE  gc.*
FROM    guide_category AS gc 
LEFT JOIN
        guide AS g 
ON      g.id_guide = gc.id_guide
WHERE   g.title IS NULL

或只是使用NOT IN

DELETE  
FROM    guide_category AS gc 
WHERE   id_guide NOT IN
        (
        SELECT  id_guide
        FROM    guide
        )
2020-05-17