MySQL update SQL statement for table B based on table A

Source: Internet
Author: User
Tags mysql in mysql update table definition in python

Recently encountered a requirement: MySQL in a table and B table have (ID, age) field, now you want to read the Age field of Table B and update it to the age field of the corresponding ID in table A, and I have a direct idea: Read B table in Python and get data in the form of {id:age}. Then update a table according to the value of each ID and age.

Two tables are defined separately and the data are as follows:

A table definition:

Field Type Comment
Id Int (11)
Name varchar (20)
Age Int (11)

Data:

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

b Table Definition

Field Type Comment
Id Int (11)
Age Int (11)

Data:

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

Python code to implement the

The code is as follows Copy Code

#-*-Encoding:utf8-*-
'''
@author: Crazyant.net
Read the (ID, age) data in table B, and then update a table sequentially;
'''
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 '

In fact, a single SQL statement can be done

Look at the code, it is simple, so the internet search the MySQL can be based on a table to update another table, the results found that the update itself to support the function of multiple table updates.

The code is as follows Copy Code

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

Using Python code, it appears to be a cannon hit the mosquito many times in one fell swoop.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.