解决使用MySQL进行update时报错: You can't specify target table '表名' for update in FROM clause

使用MySQL进行update时出现错误:
MySQL 中 You can’t specify target table ‘表名’ for update in FROM clause
翻译:不能先select出同一表中的某些值,再update这个表(在同一语句中),即不能依据某字段值做判断再来更新某字段的值。

出现问题语句:
update sc set score=(select avg(sc.score) from sc,teacher,course where teacher.t=course.t and sc.c=course.c and teacher.tname=‘叶平’) where sc.c in(select sc.c from teacher,course,sc where teacher.t=course.t and sc.c=course.c and teacher.tname=‘叶平’);

解决办法:
将SELECT出的结果再通过中间表SELECT一遍,这样就规避了错误。最好是给select后面指定列名加上distinct或者limit。

解决后语句:
update sc set score=(select a.t from (select distinct avg(sc.score) t from sc,teacher,course where teacher.t=course.t and sc.c=course.c and teacher.tname=‘叶平’) a) where sc.c in(select b.tt from (select distinct sc.c tt from teacher,course,sc where teacher.t=course.t and sc.c=course.c and teacher.tname=‘叶平’) b );

发布了1 篇原创文章 · 获赞 2 · 访问量 21

猜你喜欢

转载自blog.csdn.net/qq_37255858/article/details/104751207
今日推荐