In web development, we often need to insert data from one table into another, and sometimes we need to specify an import field, which only needs to import records that do not exist in the target table, although these can be broken down into simple SQL in the program, but with one SQL it saves a lot of code. The MySQL database as an example of the situation explained: Two tables: Inserttest and InsertTest2, the former has test dataCreateTableInserttest (IDint(4),namevarchar(12));
Insert intoInserttestValues(100,' Tom ');
Insert intoInserttestValues(101,' Tim ');
Insert intoInserttestValues(102,' Sam ');
1. If the fields of the 2 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 intoInsertTest1Select* fromInsertTest2;
2. If you want to import only the specified fields, you can use this method:
INSERT into Target table (field 1, Field 2, ...) SELECT Field 1, Field 2, ... From source table;Be sure to note that the order of the fields must be consistentInsert intoInsertTest1 (Id,name)SelectId,nickname fromInsertTest2;
3. If you need to import only 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. comparison field = Source table. comparison field);1> Insert multiple records:Insert intoInsertTest2
(ID,name)
SelectIdname
fromInserttest
where notexists(Select* fromInsertTest2
whereInserttest2.id=inserttest.id); 2> Insert a record:Insert intoInserttest
(ID,name)
SELECT100,' Susu '
From Test
WHERE notexists(Select* fromInserttest
whereinserttest.id = 100); Use test as the table name, followed by the SELECT statement to directly follow the value of the field to be inserted.
How does the MySQL database insert data from table A into table B?