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 ); 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); |