MySQL on delete错误 - 无法在FROM子句中指定更新目标表

时间:2013-10-22 10:48:59

标签: mysql

伙计们我试图使用嵌套查询从数据库中删除一些记录:

delete from imageviewer_crreviewerformdata
where imageviewer_crreviewerformdata.FormDataId in
(select distinct imageviewer_crreviewerformdata.FormDataId
from imageviewer_crreviewerformdata,imageviewer_crtask
where imageviewer_crreviewerformdata.TaskId = imageviewer_crtask.TaskId
and imageviewer_crtask.RevProtId in (1));

我得到了众所周知的mysql异常。有人可以帮助制定查询吗?

3 个答案:

答案 0 :(得分:1)

delete d 
from imageviewer_crreviewerformdata d
inner join imageviewer_crtask t on d.TaskId = t.TaskId
where t.RevProtId in (1)

答案 1 :(得分:0)

我认为它只是告诉你从查询中删除表别名

delete from imageviewer_crreviewerformdata
where FormDataId in
(select distinct imageviewer_crreviewerformdata.FormDataId
from imageviewer_crreviewerformdata,imageviewer_crtask
where imageviewer_crreviewerformdata.TaskId = imageviewer_crtask.TaskId
and imageviewer_crtask.RevProtId in (1));

答案 2 :(得分:0)

当我需要使用该表作为select的源从表中删除时,我通常创建一个临时表作为删除的参考。也许它有点传统,但它的确有效。

您需要创建一个临时表,通过连接临时表来删除,然后删除临时表。

CREATE TEMPORARY TABLE temp.tempdelete AS select distinct
imageviewer_crreviewerformdata.FormDataId
from imageviewer_crreviewerformdata,imageviewer_crtask
where imageviewer_crreviewerformdata.TaskId = imageviewer_crtask.TaskId
and imageviewer_crtask.RevProtId in (1));

然后你可以删除

DELETE FROM imageviewer_crreviewerformdata WHERE FormDataId IN (SELECT FormDataId FROM temp.tempdelete) 

然后放下临时表。

DROP TABLE temp.temptable.

这要求您有一个名为temp的文件夹。它也是一个很好的解决方案,可以在存储过程中更容易使用。