我有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是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
”.
这是您尝试实现的最佳实践.