删除不使用连接的查询

时间:2013-07-05 11:51:19

标签: mysql sql

我正在尝试删除joins tables的记录,但它无效。

我的查询是:

DELETE FROM category
WHERE  catid NOT IN(SELECT av.catid
                    FROM   category av
                           JOIN rel
                             ON rel.catid = av.catid
                           JOIN main_list
                             ON rel.webid = main_list.mainid
                    GROUP  BY av.catid)  

为什么此查询不起作用?它引发了以下错误:

#1093 - You can't specify target table 'category' for update in FROM clause

我该如何解决这个问题?我不确定错误是我做错了什么。

2 个答案:

答案 0 :(得分:6)

尝试使用LEFT JOIN

DELETE  av
FROM    category av
        LEFT JOIN rel ON rel.catid = av.catid
        LEFT JOIN main_list ON rel.webid = main_list.mainid 
WHERE   rel.catid IS NULL

请在执行此查询之前备份您的数据库。

答案 1 :(得分:1)

试试这个::

DELETE c from  category c
LEFT join rel  ON rel.catid = av.catid
LEFT JOIN main_list  ON rel.webid = main_list.mainid
where rel.catid is null 

DELETE FROM category
WHERE  catid NOT IN(
Select catid from 
(SELECT av.catid as catid
                    FROM   category av
                           JOIN rel
                             ON rel.catid = av.catid
                           JOIN main_list
                             ON rel.webid = main_list.mainid
                    GROUP  BY av.catid)  as tempCat)