我有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语法.
ON CONFLICT DO UPDATE
guarantees an atomicINSERT
orUPDATE
outcome;
provided there is no independent error,one of those two outcomes is
guaranteed,even under high concurrency. This is also known asUPSERT
–
“UPDATE
orINSERT
”.
这是您尝试实现的最佳实践.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。