mysql中删除数据的错误:You can't specify target table 'table_name' for update in FROM clause

在MySQL中,写SQL语句的时候 ,可能会遇到You can‘t specify target table ‘表名‘ for update in FROM clause这样的错误,它的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中),即不能依据某字段值做判断再来更新某字段的值。

例如:

delete from userscourselogs where id not in (select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM userscourselogs a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c INNER JOIN `userscourselogs` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt)

报异常:You can‘t specify target table ‘table_name‘ for update in FROM clause

 

将SELECT出的结果再通过中间表SELECT一遍,这样就规避了错误。

修改为

delete from userscourselogs where id not in (select id from (  select b.id as id from ( SELECT MAX(a.`ModifyAt`)ModifyAt,a.userid FROM userscourselogs a   GROUP BY a.UserId,a.SeriesId,a.CourseId) c
 INNER JOIN `userscourselogs` b ON c.userid=b.userid AND c.ModifyAt=b.ModifyAt) as d)

执行成功。

这个问题只出现于MySQL,MSSQL和Oracle不会出现此问题。

mysql中删除数据的错误:You can't specify target table 'table_name' for update in FROM clause

上一篇:MongoDB中distinct的用法


下一篇:[asp数据库同步]小门