MySQL一條語句更新多個表的方法

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.