postgresql – Postgres INSERT ON CONFLICT DO UPDATE vs INSERT或UPDATE

前端之家收集整理的这篇文章主要介绍了postgresql – Postgres INSERT ON CONFLICT DO UPDATE vs INSERT或UPDATE前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有stock_price_alert表,有3列. stock_price_id是PRIMARY 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查询,以决定是执行query(1)还是(2).

Postgres支持INSERT INTO TABLE ….关于冲突更新…:

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

而不是使用query(1)或(2),我总是可以使用query(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/238905.html

猜你在找的Postgre SQL相关文章