A-A+
	MySQL一条语句更新多个表的方法
MySQL一条语句更新多个表的方法我们会用到join子查询了,下面我们一起来看看实现方法,MySQL本身是支持一条update语句更新多个表的,有时候这是非常有用的一个特性,代码如下:
- Multiple-table syntax
 - UPDATE [LOW_PRIORITY] [IGNORE] table_references
 - SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] …
 - [WHERE where_condition]</pre>
 
于是继续找table_references说明,代码如下:
- table_references:
 - escaped_table_reference [, escaped_table_reference] …
 - escaped_table_reference:
 - table_reference
 - | { OJ table_reference }
 - table_reference:
 - table_factor
 - | join_table
 - table_factor:
 - tbl_name [[AS] alias] [index_hint]
 - | table_subquery [AS] alias
 - | ( table_references )
 
可以看到,update的关键词可以写多个表,每个表也可以是个子查询、也可以是join语句.
一个小尝试,在我的另一篇文章中,我已经用到了该语法,代码如下:
UPDATE table_a,table_b SET table_a.age=table_b.age WHERE table_a.id=table_b.id;
该语句中的table_b表也可以换成子查询、join子句,代码如下:
UPDATE table_a,(SELECT id,age FROM table_b) AS tb SET table_a.age=tb.age WHERE table_a.id=tb.id;
如果没明白我们再接一个小看一个例子就明白了,代码如下:
- create table student
 - (
 - student_id int not null
 - ,student_name varchar(30) not null
 - ,city_code varchar(10) null
 - ,city_name varchar(50) null
 - ); //www.xiaohuboke.com
 - create table city
 - (
 - code varchar(10) not null
 - ,name varchar(50) not null
 - );
 - insert into student values(1, 'john', '001', null);
 - insert into student values(2, 'nick', '002', null);
 - insert into city values('001', 'beijing');
 - insert into city values('002', 'shanghai');
 - insert into city values('003', 'shenzhen');
 
有两个表:student & city,现在需要取出 city.name 来更新 student.city_name,两表关联条件是如下代码:
- student.city_code=city.code。
 - update student s, city c
 - set s.city_name = c.name
 - where s.city_code = c.code;
 
也可以试下面的相关子查询,代码如下:
update student s set city_name = (select name from city where code = s.city_code);