将部分数据从一个SQL数据库复制到另一个



我需要将一些数据从一个数据库中的一个表复制到另一个数据库。因此,我有一个db1和table1,其中有一些列,比如column1(唯一id(、column2column3等。现在我有另一个数据库,它是第一个数据库的副本(模式被复制,它也将具有db1中预先存在的一些数据(。

所以db1/table1有记录:

column1          column2                   column3
1          12/07/2021 11:60:32         10/03/2021 01:34:00
2          02/02/2021 15:30:32         11/01/2021 15:31:32
3          12/03/2021 17:20:32         13/02/2021 15:30:32
4          12/04/2021 13:40:32         16/08/2021 15:30:34
5          12/06/2021 19:10:32         17/03/2021 15:20:31

db2/table2具有以下数据:

column1          column2                   column3
1                 null                      null
2          02/03/2021 15:30:32              null
5          22/05/2021 15:30:32         12/07/2021 15:30:32
6          22/05/2021 15:30:32         12/07/2021 15:30:32
7          22/05/2021 15:30:32         12/07/2021 15:30:32

我想将数据从db1/table1复制到db2/table2,但db2/table2中不存在的数据除外(基于用作标识符的column1(。因此,在本例中,column1值为3和4的记录不应复制到db2/table2中。

如果db2/table2中存在所有记录,我可以让它工作,但当记录丢失时,它会出错,说不存在记录。很抱歉,如果这是一个琐碎的问题,我对SQL一点都不太好,正在想办法做到这一点。谢谢。

如果您想复制table2中不存在的行,那么您可以使用not exists:

insert into db2.table2 (col1, col2, col3)
select t1.col1, t1.col2, t1.col3
from db1.table1 t1
where not exists (select 1 from db2.table2 t2 where t2.col1 = t1.col1);

以上似乎是合理的。但是,如果您想仅为匹配更新table2中的值,请将updatejoin:一起使用

update t2
set t2.col2 = t1.col2,
t2.col3 = t1.col3
from table2 t2 join
table1 t1
on t2.col1 = t1.col1;

最新更新