Implementation code for inserting data from one table into another table in MySql
A project of the company, to make a report -- there are many table structures to be associated, and finally decided to collect the data to be used into a new table, the following sql syntax needs to be used... Share it:
In web development, we often need to insert the data of one table into another table, and sometimes we need to specify the import fields, and only need to import records that do not exist in the target table, although these can be split into simple SQL in the program. Implementation, but using a sql will save a lot of code. Below I will explain one by one using the mysql
database
as an example:
1. If the fields of the two tables are consistent and you want to insert all the data, you can use this method:
1
2
|
INSERT
INTO
目标表
SELECT
*
FROM
来源表;
insert
into
insertTest
select
*
from
insertTest2;
|
2. If you only want to import specified fields, you can use this method:
1
2
|
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:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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);
|