sql - 从另一个表 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
解决方案
使用两个查询:
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;
推荐阅读
- python - S= ' ' +S + ' ' 是什么意思?为什么空间需要连接到两端?
- sql - 如何最有效地比较 Amazon Athena 中的日期组件?
- python - 如何从循环外线程中调用的函数中保存返回的值
- java - datasnapshot 没有从 firebase 获得价值
- reactjs - AWS - 我将我的 RDS 安全组的入站规则更改为某个 ip,我在访问主网站时收到 502 响应
- babeljs - 如何解决 Vue SFC 中的“解析错误:此实验性语法需要启用以下解析器插件之一:'jsx, flow, typescript'”
- python - 未找到未使用的库的 Pyinstaller 隐藏导入
- google-chrome - 在 chrome 扩展程序中使用 Microsoft 帐户?
- excel - Excel VBA宏循环遍历单元格(包括空白)到最后一个单元格的数据并替换
- php - 当产品有货时显示自定义产品徽章 WooCommerce