[转帖]MYSQL错误代码: 1093 You can't specify target table 'sc' for update in FROM claus_MySQL, Oracle及数据库讨论区_Weblogic技术|Tuxedo技术|中间件技术|Oracle论坛|JAVA论坛|Linux/Unix技术|hadoop论坛_联动北方技术论坛  
网站首页 | 关于我们 | 服务中心 | 经验交流 | 公司荣誉 | 成功案例 | 合作伙伴 | 联系我们 |
联动北方-国内领先的云技术服务提供商
»  游客             当前位置:  论坛首页 »  自由讨论区 »  MySQL, Oracle及数据库讨论区 »
总帖数
1
每页帖数
101/1页1
返回列表
0
发起投票  发起投票 发新帖子
查看: 1649 | 回复: 0   主题: [转帖]MYSQL错误代码: 1093 You can't specify target table 'sc' for update in FROM claus        下一篇 
冰释清风
注册用户
等级:新兵
经验:71
发帖:7
精华:0
注册:2016-9-26
状态:离线
发送短消息息给冰释清风 加好友    发送短消息息给冰释清风 发消息
发表于: IP:您无权察看 2018-8-16 14:55:28 | [全部帖] [楼主帖] 楼主

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

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 DELETE, INSERT, REPLACE, UPDATE, 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 t have already been selected by the time the update to t takes place.


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




赞(0)    操作        顶端 
总帖数
1
每页帖数
101/1页1
返回列表
发新帖子
请输入验证码: 点击刷新验证码
您需要登录后才可以回帖 登录 | 注册
技术讨论