1093 - You can't specify target table 'xxx' for update in FROM clause

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章