从另一个更新并插入一个 table

Update and insert to one table from another

我有两个表:

table1: (ID, Code, Name)
table2: (ID, Code, Name) 具有相同的列

我想将数据从 table1 插入到 table2 或更新 table2 中存在的列 (table1.ID = table2.ID)

执行此操作的简单方法是什么?

没有合并

假设 ID 列是唯一的并且不应设置,看来您可以在两个 SQL 语句中完成。

/* UPDATE the rows in TABLE2 */
UPDATE TABLE2
    SET NAME = (SELECT NAME FROM TABLE1 WHERE TABLE1.CODE = TABLE2.CODE)
WHERE CODE IN (SELECT CODE FROM TABLE1)

/* INSERT the rows that are missing */
INSERT INTO TABLE2
    (CODE, NAME)
    (
         SELECT CODE, NAME
         FROM TABLE1
         WHERE CODE NOT IN (SELECT CODE FROM TABLE2)
    )
MERGE table2 t2
USING table1 t1
ON t1.ID = t2.ID
WHEN MATCHED THEN
  UPDATE
  SET t2.Code = t1.Code, t2.Name = t1.Name 
WHEN NOT MATCHED BY TARGET THEN
  INSERT (ID, Name, Code)
  VALUES (t1.ID, t1.Name, t1.Code);
Merge table2 as target
using table1  as source
on
target.id=source.id
When matched 
Then
update 
set target.id=source.id,
    target.name=source.name
When not matched by Target Then
INSERT (id, name) VALUES (id, name);

Merge 语句有一些问题,所以它应该与 caution..

一起使用

此外,我建议使用合并作为两个单独的 DML 语句,如下所示..

insert into table2
select * from table1 t1 where not exists (select 1 from table2 t2 where t2.id=t1.id)

update t2
set 
t2.id=t1.id,
t2.name=t1.name
from 
table1 t1
join
table2 t2
on t1.id=t2.id

Paul White here in his detailed answer..

陈述的原因

获取表 1 中但不在表 2 中的所有行

insert into table2(id, code, name)(
SELECT table1.*
FROM table1
    LEFT JOIN table2 ON (table1.id = table2.id)
WHERE table2.C IS NULL
)

更新表 2

update table2 set name = (select name from table1 where table1.code = table2.code and table1.id = table2.id)

如果您想手动完成更新和插入,可能值得一看 triggers

这里我写了一个脚本,当你想从 table1 更新 table2 时使用 full。

    Update table2 set table2.code = table1.code, table2.name=table1.name from table1 where table2.id=table1.id

如果您想插入,请使用此脚本。

Insert into table2  (id,code,name) select id,code,name from table1

如果table2 中的id 不是自增的。 否则不在table2中插入id列的值。

将日期插入 目标 table 一旦日期在 source table 中更新 这里有一个工作示例:

create table Table1(id int,name varchar(100));
create table Table2(id int,name varchar(100));
create trigger Table1Trigger after insert on Table1 for each row begin
    insert into Table2(id, name) values (new.id, new.name);
end;

使用以下查询来验证结果

insert into Table1 values(1,'John'),(2,'Smith'),(3,'Carol');