Mysql 报错 You can’t specify target table ‘表名’ for update in FROM clause
执行mysql语句时,出现了You can’t specify target table ‘表名’ for update in FROM clause的错误。
该错误只有Mysql会出现,MSSQL和Oracle不会出现该错误。
sql是这样的:
UPDATE account set status=1 where id in ( select id from account where ISNULL(status));
查找表中status字段为空的,并把其更改为1。错误的意思是,不能先select出同一表中的某些值,再update这个表(在同一语句中),即不能依据某字段值做判断再来更新某字段的值。
解决方案
使用中间表来规避错误,即先select的结果再使用中间表select一遍。
修改后sql如下:
UPDATE account set status=1 where id in (
select a.id from
(select id from account where ISNULL(status)) a);