最近遇到一个需求:mysql中A表和B表都有(id, age)字段,现在想读取B表的age字段,将其update到A表对应ID的age字段中去,我直接想到了一种方案:用Python读取B表,获得{id:age}形式的数据,然后根据每个ID和age的值依次update A表。 两个表分别定义和数据如下
最近遇到一个需求:mysql中A表和B表都有(id, age)字段,现在想读取B表的age字段,将其update到A表对应ID的age字段中去,我直接想到了一种方案:用Python读取B表,获得{id:age}形式的数据,然后根据每个ID和age的值依次update 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
# -*- 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' ?
看了看代码,实在是简单,于是网上搜了一下mysql能不能根据一个表更新另一个表,结果发现update本身就支持多个表更新的功能。
UPDATE table_a,table_b SET table_a.age=table_b.age WHERE table_a.id=table_b.id;
用python代码就显得是大炮打蚊子多次一举了。
转载请注明来源:链接
原文地址:mysql根据A表更新B表的方法, 感谢原作者分享。
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号