MySQL版本:5.7.20
操作表数据结构如下:
一 需求
将下级部门和上级部门关联,更新下级部门的parent_id 字段为上级部门的id字段值,SQL语句如下:
UPDATE department set parent_id=
(select id from department where department_name = 'dep_1')
where department_level ='2';
报错如下:
[Err] 1093 - You can't specify target table 'department' for update in FROM clause
意思是FROM 条件中不能指定要更新的目标表,看来MySQL并不支持这种子查询方式的更新操作,MySQL手册也对该问题作了说明:
“This error occurs in cases such as the following, which attempts to modify a table and select from the same table in the subquery:
UPDATE t1 SET column2 = (SELECT MAX(column1) FROM t1);”
二 解决方法
将子查询作为临时表,然后选择临时表相关字段作为条件值进行更新。
更新语句如下:
UPDATE department,
(select id from department where department_name = 'dep_1') temp
set parent_id = temp.id
where department_level ='2';
执行后结果如下:
参考:MySQL :: MySQL 5.7 Reference Manual :: 13.2.10.9 Subquery Errors