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