MYSQL错误代码: 1093 You can't specify target table 'sc' for update in FROM clause

 ̄綄美尐妖づ 提交于 2020-01-16 08:37:07

MYSQL执行如下语句报错:

UPDATE sc SET grade =grade*1.05 WHERE grade < (SELECT AVG(grade) AS avg_grade FROM sc) 

报错信息如下:

  错误代码: 1093
  You can't specify target table 'sc' for update in FROM clause

意思是不能在同一语句中更新select出的同一张表元组的属性值

解决方法:将select出的结果通过中间表再select一遍即可。

UPDATE sc SET grade =grade*1.05 WHERE grade < (SELECT avg_grade FROM (SELECT AVG(grade) AS avg_grade FROM sc) AS temp)

 

MYSQL手册sql-syntax.html里是这么写的:

Incorrectly used table in subquery:

Error 1093 (ER_UPDATE_TABLE_USED)
SQLSTATE = HY000
Message = "You can't specify target table 'x'
for update in FROM clause"

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);

You can use a subquery for assignment within an UPDATE statement because subqueries are legal in UPDATE andDELETE statements as well as in SELECT statements. However, you cannot use the same table (in this case, tablet1) for both the subquery FROM clause and the update target.

 

In MySQL, you cannot modify a table and select from the same table in a subquery. This applies to statements such as DELETEINSERTREPLACEUPDATE, and (because subqueries can be used in the SET clause) LOAD DATA INFILE.

 

MYSQL手册restrictions.html#subquery-restrictions里给出了限制规则和解决方法:

In general, you cannot modify a table and select from the same table in a subquery. For example, this limitation applies to statements of the following forms:

DELETE FROM t WHERE ... (SELECT ... FROM t ...);
UPDATE t ... WHERE col = (SELECT ... FROM t ...);
{INSERT|REPLACE} INTO t (SELECT ... FROM t ...);

Exception: The preceding prohibition does not apply if you are using a subquery for the modified table in the FROM clause. Example:

UPDATE t ... WHERE col = (SELECT * FROM (SELECT ... FROM t...) AS _t ...);

Here the result from the subquery in the FROM clause is stored as a temporary table, so the relevant rows in have already been selected by the time the update to t takes place.

其实想想也是这样的,对同一张表查的同时更新会引起数据不一致的问题吧,但是将查询结果事先放到临时表中就不会有这个问题了。

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!