mysql出现“ You can't specify target table '表名' for update in FROM clause”解决方法
You can't specify target table '表名' for update in FROM clause
翻译为:不能先select出同一表中的某些值,再update这个表(在同一语句中)
实例:
表:result
表student
表:grade
要求:给大一成绩不合格的分数加5分
思路:
第一步:查询出大一成绩不合格的成绩集合
SELECT res.StudentResult
FROM student stu
JOIN result res on res.StudentNo=res.StudentNo
where res.StudentResult<60 and stu.GradeId=(SELECT GradeId
FROM grade
WHERE GradeName='大一'
)
第二步:修改不合格成绩
UPDATE result
SET StudentResult=StudentResult+5
WHERE StudentResult in(
(SELECT res.StudentResult
FROM student stu
JOIN result res on res.StudentNo=res.StudentNo
where res.StudentResult=53 and stu.GradeId=(SELECT GradeId
FROM grade
WHERE GradeName='大一'
)
)
)
此时报错:1093 - You can't specify target table 'result' for update in FROM clause
正确写法应该是:
UPDATE result
SET StudentResult=StudentResult+5
WHERE StudentResult in(
SELECT a.StudentResult from
(SELECT res.StudentResult
FROM student stu
JOIN result res on res.StudentNo=res.StudentNo
where res.StudentResult=53 and stu.GradeId=(SELECT GradeId
FROM grade
WHERE GradeName='大一'
)
) AS a
)
也就是说:把结果集当作一个表,自我查询一遍
格式为:SELECT a.StudentResult FROM
(结果集)a
本文来自博客园,作者:King-DA,转载请注明原文链接:https://www.cnblogs.com/qingmuchuanqi48/p/13605337.html