A-A+

MySQL一条语句更新多个表的方法

2017年10月23日 PHP技术文章 暂无评论 阅读 0 views 次

MySQL一条语句更新多个表的方法我们会用到join子查询了,下面我们一起来看看实现方法,MySQL本身是支持一条update语句更新多个表的,有时候这是非常有用的一个特性,代码如下:

  1. Multiple-table syntax   
  2. UPDATE [LOW_PRIORITY] [IGNORE] table_references   
  3.     SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] …   
  4.     [WHERE where_condition]</pre>   

于是继续找table_references说明,代码如下:

  1. table_references:   
  2.     escaped_table_reference [, escaped_table_reference] …   
  3. escaped_table_reference:   
  4.     table_reference   
  5.   | { OJ table_reference }   
  6. table_reference:   
  7.     table_factor   
  8.   | join_table   
  9. table_factor:   
  10.     tbl_name [[AS] alias] [index_hint]   
  11.   | table_subquery [AS] alias   
  12.   | ( 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;
如果没明白我们再接一个小看一个例子就明白了,代码如下:

  1. create table student   
  2. (   
  3.    student_id    int          not null   
  4.   ,student_name  varchar(30)  not null   
  5.   ,city_code     varchar(10)  null   
  6.   ,city_name     varchar(50)  null   
  7. ); //www.xiariboke.net  
  8. create table city   
  9. (   
  10.    code varchar(10) not null   
  11.   ,name varchar(50) not null   
  12. );   
  13. insert into student values(1, 'john', '001', null);   
  14. insert into student values(2, 'nick', '002', null);   
  15. insert into city values('001', 'beijing');   
  16. insert into city values('002', 'shanghai');   
  17. insert into city values('003', 'shenzhen');   

有两个表:student & city,现在需要取出 city.name 来更新 student.city_name,两表关联条件是如下代码:

  1. student.city_code=city.code。   
  2. update student s, city c   
  3.    set s.city_name = c.name   
  4.  where s.city_code = c.code;   

也可以试下面的相关子查询,代码如下:

update student s set city_name = (select name from city where code = s.city_code);

标签:

给我留言