MySQL不容许SELECT FROM后面指向用做UPDATE的表,有时候让人纠结。本文解释如何UPDATE一张表,同时在查询子句中使用SELECT. 问题描述 假设我要UPDATE的表跟查询子句是同一张表,这样作有许多种缘由,例如用统计数据更新表的字段(此时须要用group子句返回统计值),从某一条记录的字段update另外一条记录,而没必要使用非标准的语句,等等。举个例子:app
create table apples(variety char(10) primary key, price int);ci
insert into apples values('fuji', 5), ('gala', 6);get
update apples
set price = (select price from apples where variety = 'gala')
where variety = 'fuji';io
错误提示是:ERROR 1093 (HY000): You can't specify target table 'apples' for update in FROM clause. MySQL手册UPDATE documentation这下面有说明 : “Currently, you cannot update a table and select from the same table in a subquery.” 在这个例子中,要解决问题也十分简单,但有时候不得不经过查询子句来update目标。好在咱们有办法。table
解决办法 既然MySQL是经过临时表来实现FROM子句里面的嵌套查询,那么把嵌套查询装进另一个嵌套查询里,可以使FROM子句查询和保存都是在临时表里进行,而后间接地在外围查询被引用。下面的语句是正确的:date
update apples
set price = (
select price from (
select * from apples
) as x
where variety = 'gala')
where variety = 'fuji';select