MySQL in a table of data inserted into another table implementation Code division of a project, do a report-the table to be associated with more structure, and finally decided to use the data into a new table, need to use the following SQL syntax ... Share: In Web development, we often need to insert data from one table into another, and sometimes we need to specify an import field that 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. Here I take the MySQL database as an example of the situation explained: 1. If the fields of 2 tables are consistent and you want to insert all the data, you can use this method:?
12 |
INSERT INTO 目标表 SELECT * FROM 来源表; insert into insertTest select * from insertTest2; |
2. If you want to import only the specified fields, you can use this method:?
12 |
INSERT INTO 目标表 (字段1, 字段2, ...) SELECT 字段1, 字段2, ... FROM 来源表;(这里的话字段必须保持一致) insert into insertTest2(id) select id from insertTest2; |
3. If you need to import only records that do not exist in the target table, you can use this method:?
12345678910111213141516171819202122 |
INSERT INTO 目标表
(字段1, 字段2, ...)
SELECT 字段1, 字段2, ...
FROM 来源表
WHERE not exists (
select *
from 目标表
where 目标表.比较字段 = 来源表.比较字段);
1>.插入多条记录:
insert into insertTest2
(id,
name
)
select id,
name
from insertTest
where not exists (
select *
from insertTest2
where insertTest2.id=insertTest.id);
2>.插入一条记录:
insert into insertTest
(id,
name
)
SELECT 100,
‘liudehua‘
FROM dual
WHERE not exists (
select *
from insertTest
where insertTest.id = 100);
|
Original: http://www.2cto.com/database/201307/226259.html
The implementation code in MySQL that inserts data from one table into another table--goes