从其他表向表中插入新记录

时间:2018-07-31 03:53:53

标签: sql

我有两个表,其中表1是主表。如何将表2和表3中不存在的所有记录插入表1中?

表1:

+-----------------------------+
| REC_NUM | F_NAMES | L_NAMES | 
+-----------------------------+
|    1    |  JOHN   |  SMITH  |
+-----------------------------+
|    2    |  JAMES  |  BROWN  |
+-----------------------------+
|    3    |  BRYAN  |  KENNY  | <= Not Existing in Table 2 and 3
+-----------------------------+

表2:

+-----------------------------+
| REC_NUM | F_NAMES | L_NAMES | 
+-----------------------------+
|    1    |  JOHN   |  SMITH  |
+-----------------------------+
|    2    |  MARY   |  JANE   | <= Not Existing in TABLE 1
+-----------------------------+
|    3    |  WILL   |  BROWN  | <= Not Existing in TABLE 1
+-----------------------------+
|    4    |  JAMES  |  BROWN  |
+-----------------------------+

表3:

+-----------------------------+
| REC_NUM | F_NAMES | L_NAMES | 
+-----------------------------+
|    1    |  JOHN   |  SMITH  |
+-----------------------------+
|    2    |  STAN   |  CRAIG  | <= Not Existing in TABLE 1
+-----------------------------+
|    3    |  JAMES  |  BROWN  | 
+-----------------------------+

结果将是... 表1:

+-----------------------------+
| REC_NUM | F_NAMES | L_NAMES | 
+-----------------------------+
|    1    |  JOHN   |  SMITH  |
+-----------------------------+
|    2    |  JAMES  |  BROWN  |
+-----------------------------+
|    3    |  BRYAN  |  KENNY  |
+-----------------------------+
|    5    |  MARY   |  JANE   | <= New Record from TABLE 2
+-----------------------------+
|    6    |  WILL   |  BROWN  | <= New Record from TABLE 2
+-----------------------------+
|    7    |  STAN   |  CRAIG  | <= New Record from TABLE 3
+-----------------------------+

2 个答案:

答案 0 :(得分:0)

尝试这个:

insert into table_1 (f_names, l_names)
select f_names, l_names
from table_2 t2
where not exists (select 1 from table_1 t1 where t1.f_names = t2.f_names and t1.l_names = t2.l_names)

union

select f_names, l_names
from table_3 t3
where not exists (select 1 from table_1 t1 where t1.f_names = t3.f_names and t1.l_names = t3.l_names);

如果REC_NUM自动递增,则此sql将正常工作。

答案 1 :(得分:0)

以下在MS SQL Server中的查询将起作用。

;WITH CTE_Table2AndTable3 AS
(
SELECT REC_NUM, F_Names, L_Names FROM Table2
UNION 
SELECT REC_NUM, F_Names, L_Names FROM Table3
)
MERGE Table1 AS target
USING CTE_Table2AndTable3 AS source
ON target.REC_NUM = source.REC_NUM AND target.F_Names = source.F_Names AND target.L_Names = source.L_Names
WHEN NOT MATCHED THEN
INSERT (REC_NUM, F_Names, L_Names)
VALUES (source.REC_NUM, source.F_Names, source.L_Names);