Implementation code _ MySql

Source: Internet
Author: User
Implementation code bitsCN.com in MySql to insert data from one table to another

Implementation code of inserting data from one table into another table in MySql

In a project of the division, make a report -- the table structure to be associated is relatively large, and finally decide to merge the dataset to be used into a new table. the following SQL syntax is required ...... share:

In web development, we often need to insert data from a table to another table. sometimes, we also need to specify the import field to import records that do not exist in the target table, although these can be split into simple SQL statements in the program, using one SQL statement will save a lot of code. The following uses the mysql database as an example to describe the situation one by one:

1. if the fields of the two tables are consistent and you want to insert all the data, you can use this method:

Insert into target table SELECT * from source table; insert into insertTest select * from insertTest2;

2. if you only want to import specified fields, you can use this method:

Insert into target table (Field 1, field 2 ,...) SELECT Field 1, field 2 ,... FROM source table; (the fields must be consistent here) insert into insertTest2 (id) select id from insertTest2;

3. if you only need to import records that do not exist in the target table, you can use this method:

  

Insert into target table (Field 1, field 2 ,...) SELECT Field 1, field 2 ,... FROM source table WHERE not exists (select * from target table where Target table. compare field = source table. compare fields); 1>. insert multiple records: insert into insertTest2 (id, name) select id, namefrom insertTestwhere not exists (select * from insertTest2where insertTest2.id = insertTest. id); 2>. insert a record: insert into insertTest (id, name) SELECT 100, 'liudehua' FROM dual WHERE not exists (select * from insertTest where insertTest. id = 100 );

BitsCN.com

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.