You can’t specify target table ‘xx’ for update in FROM clause
当更新查询出来的表的值时,会出现如上问题。
需求:想更新查询出来的表数据的某些值。
例如:更新地区表中fatherid为0的级别(level)为1:
1.查出所有的fatherid为0的地区数据
SELECT t1.districtid FROM ta_district t1 WHERE t1.fatherid = 0
如图:
2.若直接更新查询出的数据即会报错,如图:
如图:
3.需要先把查询出来的结果集当做一个表,自我查询一遍,再执行更新操作。
UPDATE ta_district
SET LEVEL = 1
WHERE
districtid IN (
SELECT
newTable.districtid
FROM
( SELECT t1.districtid FROM ta_district t1 WHERE t1.fatherid = 0 ) AS newTable)
如图 成功: