您的位置:首页 > 数据库 > MySQL

MySQL:You can’t specify target table ‘A’ for update in FROM clause

2015-10-27 15:21 549 查看
按照MYSQL5.0文档的解释:我们不能在修改表A的同时在其子查询中使用到表A,但是可以通过在子查询中在嵌套一层针对表A的子查询,因为最里层的子查询产生的结果存在临时表中,与表A没有关系。

解决方法:把类似于 UPDATE t ... WHERE col = (SELECT ... FROM t ...); 改写成UPDATE t ... WHERE col = (SELECT (SELECT ... FROM t...) AS _t ...);即可。

文档原文: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 (SELECT ... FROM t...) AS _t ...);

Here the prohibition does not apply because a subquery in the

FROM

clause is materialized as a temporary table, so the relevant rows in

t

have already been selected by the time the update to

t
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sql mysql specify target table