国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 數據庫 > MySQL > 正文

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

2024-07-24 12:36:50
字體:
來源:轉載
供稿:網友

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語句.

一個小嘗試,在我的另一篇文章中,我已經用到了該語法,代碼如下:

  1. UPDATE table_a,table_b SET table_a.age=table_b.age WHERE table_a.id=table_b.id; 

該語句中的table_b表也可以換成子查詢、join子句,代碼如下:

  1. 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.    student_id    int          not null 
  3.   ,student_name  varchar(30)  not null 
  4.   ,city_code     varchar(10)  null 
  5.   ,city_name     varchar(50)  null 
  6. ); //Vevb.com
  7. create table city 
  8.    code varchar(10) not null 
  9.   ,name varchar(50) not null 
  10. ); 
  11. insert into student values(1, 'john''001'null); 
  12. insert into student values(2, 'nick''002'null); 
  13. insert into city values('001''beijing'); 
  14. insert into city values('002''shanghai'); 
  15. 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);

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 论坛| 柯坪县| 赣州市| 临澧县| 陵水| 宜兰县| 久治县| 上栗县| 怀集县| 波密县| 神池县| 本溪| 莱西市| 邢台市| 呼图壁县| 伊金霍洛旗| 留坝县| 东乡| 察雅县| 白银市| 大理市| 望谟县| 宽城| 靖宇县| 宿州市| 同德县| 密山市| 修武县| 郸城县| 突泉县| 玛曲县| 临武县| 贵德县| 铜山县| 那坡县| 曲沃县| 庄浪县| 静海县| 邮箱| 郓城县| 南丹县|