Mysql报错ERROR 1093

今天碰到一个mysql的错误,这里与大家分享一下,在mysql中执行以下语句:

update monitor set Endtime = "10:01:13" 
where Id = 
(select max(Id) from monitor  where Portaljid = "portal" and Pathid = "path_A" )

这是会产生一个错误:

ERROR 1093 (HY000): You can't specify target table 'A' for update in FROM clause

查阅了mysql官网文档中:

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 takes place.

在存在子查询语句时,如果子查询语句用的表与父查询用的一样,就会报上面的错误,文档中也给出了解决方案,就是使用临时表。
将上面的sql语句修改如下即可。

update monitor set Endtime = "10:01:13" 
where Id = 
(select max(temp.id) from (select m.id from monitor m) temp where Portaljid = "portal" and Pathid = "path_A")

这里使用了中转的临时表

本站总访问量