You can't specify target table 'sc' for update in FROM clause Mysql报错

例题

在sc表中修改005号课程的成绩,如果成绩低于75,则提高5%

sc表

 

 第一次尝试

update sc
set grade = grade*1.05
where sno in( 
select sno 
from sc 
where course = '005' and grade<75);

报错:You can't specify target table 'sc' for update in FROM clause 

错误的意思是说,不能先select出同一表中的某些值,再update这个表(在同一语句中)。

改进后

update sc
set grade = grade*1.05
where sno in( 
SELECT h.sno FROM
(select sno 
from sc 
where cno = '0005' and grade<75
) h
);

将SELECT出的结果再通过中间表SELECT一遍,这样就规避了错误。

运行结果于要求相同

 

posted @ 2022-04-16 19:43  YUYUUUU  阅读(200)  评论(0编辑  收藏  举报