gpt4 book ai didi

postgresql - Postgres INSERT ON CONFLICT DO UPDATE 与 INSERT 或 UPDATE

转载 作者:行者123 更新时间:2023-11-29 11:14:50 24 4
gpt4 key购买 nike

我有包含 3 列的 stock_price_alert 表。 stock_price_idPRIMARY KEY 也是 FOREIGN KEY 到其他表。表定义如下:

create table stock_price_alert (
stock_price_id integer references stock_price (id) on delete cascade not null,
fall_below_alert boolean not null,
rise_above_alert boolean not null,
primary key (stock_price_id)
);

我需要:

1) INSERT 如果不存在则记录

-- query 1
INSERT INTO stock_price_alert (stock_price_id, fall_below_alert, rise_above_alert)
VALUES (1, true, false);

2) UPDATE 记录是否存在

-- query 2
UPDATE stock_price_alert SET
fall_below_alert = true,
rise_above_alert = false
WHERE stock_price_id = 1;

首先,我需要对 stock_price_alert 表发出 SELECT 查询,以决定是执行查询 (1) 还是 (2)。

Postgres 支持 INSERT INTO TABLE .... ON CONFLICT DO UPDATE ...:

-- query 3
INSERT INTO stock_price_alert (stock_price_id, fall_below_alert, rise_above_alert)
VALUES (1, true, false)
ON CONFLICT (stock_price_id) DO UPDATE SET
fall_below_alert = EXCLUDED.fall_below_alert,
rise_above_alert = EXCLUDED.rise_above_alert;

除了使用查询 (1) 或 (2),我可以始终使用查询 (3) 吗?然后我不需要在之前发出 SELECT 查询,它有助于简化代码。

但我想知道,哪种做法是最佳做法?查询 (3) 会导致性能问题或不良副作用吗?谢谢。

最佳答案

查询 3 是 Postgres 9.5 中引入的“UPSERT”(= UPDATE 或 INSERT)的 Postgres 语法。

来自documentation :

ON CONFLICT DO UPDATE guarantees an atomic INSERT or UPDATE outcome; provided there is no independent error, one of those two outcomes is guaranteed, even under high concurrency. This is also known as UPSERT – “UPDATE or INSERT”.

这是您要实现的最佳实践。

关于postgresql - Postgres INSERT ON CONFLICT DO UPDATE 与 INSERT 或 UPDATE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48922972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com