postgresql - 哪种方法更适合 PostgreSQL 中的 UPSERT?
问题描述
在阅读如何在 PostgreSQL 中进行 UPSERT (MERGE, INSERT ... ON DUPLICATE UPDATE) 之后?我很好奇哪种方法对 UPSERT 更好(更快)。
我目前正在编写一个应用程序,在大多数情况下,数据只更新(新行很少见),因此我认为最好使用这种方法而不尝试先插入(来自Postgres DOCS):
CREATE FUNCTION merge_db(key INT, data TEXT) RETURNS VOID AS
$$
BEGIN
LOOP
-- first try to update the key
UPDATE db SET b = data WHERE a = key;
IF found THEN
RETURN;
END IF;
-- not there, so try to insert the key
-- if someone else inserts the same key concurrently,
-- we could get a unique-key failure
BEGIN
INSERT INTO db(a,b) VALUES (key, data);
RETURN;
EXCEPTION WHEN unique_violation THEN
-- Do nothing, and loop to try the UPDATE again.
END;
END LOOP;
END;
$$
LANGUAGE plpgsql;
还是会更好用INSERT ... ON CONFLICT DO UPDATE
?
解决方案
推荐阅读
- node.js - 如何使用 CNG 密钥使用 JwtSecurityTokenHandler 签名的 Nodejs 工具使用 ES384 算法验证 JWT 令牌
- webpack - Webpack 未完成就冻结
- c# - 如何在 C# 中保存面板并恢复它?
- reactjs - Discord oAuth 与本机反应
- encryption - 关于英特尔 SGX 模拟器与基于 Rust 的客户端的兼容性的查询
- azure - VS 2019 表格模型显示空白值
- java - 尝试使用 KafkaAdmin.NewTopics 创建 kafka 主题,但 KafkaListener 设法在它之前创建一个主题
- python - Python:转置列和重复行
- php - 如何将字符串转换为关联数组?
- python - 如何在python中隐藏默认错误消息(Traceback)