MySQL 中 You can't specify target table '表名' for update in FROM clause错误解决办法

执行这条SQL语句时报错

DELETE FROM tableName WHERE id NOT IN ( SELECT id FROM tableName GROUP BY date );

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

解决方法:

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

DELETE
FROM
tableName
WHERE
id NOT IN ( SELECT a.id FROM ( SELECT id FROM tableName GROUP BY date ) AS a );

 

上一篇:MySQL 0 IN(“Some”,“Set”)


下一篇:mysql出现 Unknown column 'bname' in 'where clause'和Unknown column 'bid'