首页 > 解决方案 > 从另一个表 postgres 更新表时如何执行 upsert?

问题描述

我有A一个包含大约 1000 万行的表,而 TableB包含 table 中某些行的一些更新信息,A还包含 table 中不存在的新行A

我想A使用 table更新 tableB并同时插入 table 中不匹配的行A

我找到了许多类似下面的解决方案的答案,但似乎他们都错过了我正在寻找的插入部分。

UPDATE A 
SET code = B.code
FROM B
WHERE A.id = B.id 

标签: sqlpostgresql

解决方案


使用两个查询:

update a
    set code = b.code
    from b
    where a.id = b.id;

insert into a (id, code)
    select id, code
    from b
    where not exists (select 1 from a where a.id = b.id);

你也可以使用on conflict

insert into a (id, code)
    select b.id, b.code
    on conflict on constraint a_id
    do update set code = b.code;

推荐阅读