【发布时间】:2018-08-02 00:59: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,
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;
我可以始终使用查询 (3),而不是使用查询 (1) 或 (2)?然后我不需要事先发出SELECT 查询,它有助于简化代码。
但我想知道,最佳做法是什么?查询 (3) 会导致性能问题或不必要的副作用吗?谢谢。
【问题讨论】:
标签: postgresql sql-update sql-insert