MySQL中You can't specify target table for update in FROM clause 错误的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)。
例如下面这个sql(会报错):
#根据 student_family表中的姓名,更新其表中的字段值
update student_family set gbbz='是'
where xm in (select f.xm fxm from student_family f where f.familyid = '13');
执行SQL语句时出现这个错误。原因是在更新这个表和数据时又查询了它,而查询的数据又做了更新的条件。注意,这个问题只出现于MySQL.
解决方法:1,把要更新的几列数据查询出来做为一个第三方表,然后筛选更新(推荐使用)。
update student_family set gbbz='是'
where xm in (select f.xm fxm from (select v.xm,v.familyid from student_family v) f where f.familyid = '13');
2,新建一个临时表保存查询出的数据,然后筛选更新。最后删除临时表(不推荐)。
毫毛疑问使用第一种方法要好。