MySQL不允许SELECT FROM后面指向用作UPDATE的表,有时候让人纠结。当然,有比创建无休止的临时表更好的办法。本文解释如何UPDATE一张表,同时在查询子句中使用SELECT.

问题描述

假设我要UPDATE的表跟查询子句是同一张表,这样做有许多种原因,例如用统计数据更新表的字段(此时需要用group子句返回统计值),从某一条记录的字段update另一条记录,而不必使用非标准的语句,等等。举个例子:

1
2
create table apples(variety char(10) primary key, price int);
insert into apples values('fuji', 5), ('gala', 6);
1
2
3
4
update apples

set price = (select price from apples where variety = 'gala')
where variety = 'fuji';
1
错误提示是: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目标。好在我们有办法。

解决办法

既然MySQL是通过临时表来实现FROM子句里面的嵌套查询,那么把嵌套查询装进另外一个嵌套查询里,可使FROM子句查询和保存都是在临时表里进行,然后间接地在外围查询被引用。下面的语句是正确的:

1
2
3
4
5
6
7
8
9
10
11
12
13
update apples

set price = (

select price from (

select * from apples

) as x

where variety = 'gala')

where variety = 'fuji';

在遇到需要update设置的参数来自从其他表select出的结果时,需要把update和select结合使用,不同数据库支持的形式不一样,在mysql中如下:

1
2
update A inner join(select id,name from B) c on A.id = c.id set A.name = c.name;

根据AB两个表的id相同为条件,把A表的name修改为B的sql语句就如上所示