The method for copying MySQL query results to a new table (update and insert) and mysql query results

Source: Internet
Author: User

The method for copying MySQL query results to a new table (update and insert) and mysql query results

In MySQL, you can copy the query results to another table. there are usually two types of replication: update existing data and insert a new record. The following is an example. First, construct two test tables.

Table t1:

Table t2:

1. If score Values exist in Table t2, update the score to table t1. The method is as follows:

UPDATE t1, t2
SET t1.score = t2.score
WHERE t1.id = t2.id AND t2.score IS NOT NULL

This is to update another table using the query result as a condition. Of course, t2 can also be a more complex query result rather than a specific table.

2. Update the username of table t1 to table t2 and the score of table t2 to table t1. The method is as follows:

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. You can update the data of two tables at the same time, that is, copying and updating some of the table data.

3. Insert the query results of table t2 to table t1. The method is as follows:

Insert into t1 (id, username, score)
SELECT t2.id, t2.username, t2.score FROM t2 where t2.username = 'Lucy'

The first two methods are to update the table record, which is to insert a new record. In fact, we can see from the script that this method is to combine the query and insert steps into one.

The preceding section describes how to copy MySQL query results to a new table (update and insert ~

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.