MySQL query results copied to new table (update, insert)

Source: Internet
Author: User
Tags mysql query

MySQL query results copied to new table (UPDATE, insert):

MySQL can copy query results to another table, there are usually two cases of replication, one is to update the existing data, the other is to insert a new record. This is illustrated by an example below. Build two test tables first.

Table T1:

Table T2:

1. If the score value exists in the T2 table, the score is updated to the T1 table. Here's how:

UPDATE t1,t2 SET t1.score = t2.score WHERE t1.id = t2.id and T2.score is not NULL

This is to update the query result as a condition for another table, of course, T2 can also be a more complex query result rather than a specific table.

2. Update the username of the T1 table to the T2 table, and update the score of the T2 table to the T1 table. Here's how:

UPDATE t1,t2 SET t1.score = T2.score,t2.username = t1.username WHERE t1.id = t2.id

This method is similar to the above method, can update the data of two tables at the same time, that is, the table part of the data replication, update.

3. Insert the query results of the T2 table into the T1 table. Here's how:

INSERT into T1 (id,username,score) SELECT t2.id,t2.username,t2.score from t2 where t2.username = ' Lucy '

The first two ways to update a table's records is to insert a new record. In fact, as can be seen from the script, this method is to merge the query and insert two steps into one.

MySQL query results copied to new table (update, insert)

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.