mysql update根據A表更新B表的sql語句

來源:互聯網
上載者:User

最近遇到一個需求:mysql中A表和B表都有(id, age)欄位,現在想讀取B表的age欄位,將其update到A表對應ID的age欄位中去,我直接想到了一種方案:用Python讀取B表,獲得{id:age}形式的資料,然後根據每個ID和age的值依次update A表。

兩個表分別定義和資料如下:

A表定義:

Field Type Comment
id int(11)  
name varchar(20)  
age int(11)  

資料:

1,name1,0
2,name2,0
3,name3,0
4,name4,0
5,name5,0

B表定義

Field Type Comment
id int(11)  
age int(11)  

資料:

1,11
2,21
3,31
4,41
5,51

python代碼來實現

 代碼如下 複製代碼

# -*- encoding:utf8 -*-
'''
@author: crazyant.net
讀取B表的(id, age)資料,然後依次更新A表;
'''
from common.DBUtil import DB

dbUtil = DB('127.0.0.1',3306,'root','','test')

rs = dbUtil.query("SELECT id,age FROM table_b")

for row in rs:
    (idv,age)=row
    print (idv,age)
    update_sql="update table_a set age='%s' where id='%s';"%(age,idv)
    print update_sql
    dbUtil.update(update_sql)

print 'over'

其實一條SQL語句就可以搞定

 看了看代碼,實在是簡單,於是網上搜了一下mysql能不能根據一個表更新另一個表,結果發現update本身就支援多個表更新的功能。

 代碼如下 複製代碼

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

用python代碼就顯得是大炮打蚊子多次一舉了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.