加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql – Postgres INSERT ON CONFLICT DO UPDATE vs INSER

发布时间:2020-12-13 18:05:25 所属栏目:百科 来源:网络整理
导读:我有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
我有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”.

这是您尝试实现的最佳实践.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读