如Insert, on duplicate update in PostgreSQL?
中所述,可写CTE被认为是9.5之前的UPSERT的解决方案可以执行UPSERT,其中包含最终为UPDATE的信息或具有以下可写CTE惯用语的INSERT:
WITH
update_cte AS (
UPDATE t SET v = $1 WHERE id = $2 RETURNING 'updated'::text status
),
insert_cte AS (
INSERT INTO t(id, v) SELECT $2, $1 WHERE NOT EXISTS
(SELECT 1 FROM update_cte) RETURNING 'inserted'::text status
)
(SELECT status FROM update_cte) UNION (SELECT status FROM insert_cte)
此查询将返回“已更新”或“已插入”,或者可能(很少)因违反约束而失败,如https://dba.stackexchange.com/questions/78510/why-is-cte-open-to-lost-updates
中所述使用PostgreSQL 9.5+新的“UPSERT”语法可以实现类似的功能,从优化中获益并避免可能的约束违规吗?
答案 0 :(得分:12)
我相信xmax::text::int > 0
是最简单的伎俩:
so=# DROP TABLE IF EXISTS tab;
NOTICE: table "tab" does not exist, skipping
DROP TABLE
so=# CREATE TABLE tab(id INT PRIMARY KEY, col text);
CREATE TABLE
so=# INSERT INTO tab(id, col) VALUES (1,'a'), (2, 'b');
INSERT 0 2
so=# INSERT INTO tab(id, col)
VALUES (3, 'c'), (4, 'd'), (1,'aaaa')
ON CONFLICT (id) DO UPDATE SET col = EXCLUDED.col
returning *,case when xmax::text::int > 0 then 'updated' else 'inserted' end,ctid;
id | col | case | ctid
----+------+----------+-------
3 | c | inserted | (0,3)
4 | d | inserted | (0,4)
1 | aaaa | updated | (0,5)
(3 rows)
INSERT 0 3
so=# INSERT INTO tab(id, col)
VALUES (3, 'c'), (4, 'd'), (1,'aaaa')
ON CONFLICT (id) DO UPDATE SET col = EXCLUDED.col
returning *,case when xmax::text::int > 0 then 'updated' else 'inserted' end,ctid;
id | col | case | ctid
----+------+---------+-------
3 | c | updated | (0,6)
4 | d | updated | (0,7)
1 | aaaa | updated | (0,8)
(3 rows)
INSERT 0 3
答案 1 :(得分:7)
从@lad2025's answer绘图,可以通过在WHERE子句中滥用settings和customized options与related functions来获得所需的副作用来实现结果。
CREATE TABLE t(id INT PRIMARY KEY, v TEXT);
INSERT INTO t (id, v)
SELECT $1, $2
WHERE 'inserted' = set_config('upsert.action', 'inserted', true)
ON CONFLICT (id) DO UPDATE
SET v = EXCLUDED.v
WHERE 'updated' = set_config('upsert.action', 'updated', true)
RETURNING current_setting('upsert.action') AS "upsert.action";
set_config
的第三个参数是is_local
:true
表示设置将在交易结束时消失。更确切地说,current_setting('upsert.action')
将返回NULL(并且不会抛出错误),直到会话结束。
答案 2 :(得分:5)
在SQL Server
MERGE
语句中$action
返回字符串'INSERT', 'UPDATE', or 'DELETE'
。
对于Postgresql
,我无法找到与RETURNING
类似的函数/变量。
解决方法之一是将列is_updated
添加到您的表中:
DROP TABLE IF EXISTS tab;
CREATE TABLE tab(id INT PRIMARY KEY, col VARCHAR(100),
is_updated BOOLEAN DEFAULT false);
INSERT INTO tab(id, col) VALUES (1,'a'), (2, 'b');
-- main query
INSERT INTO tab(id, col)
VALUES (3, 'c'), (4, 'd'), (1,'aaaa')
ON CONFLICT (id) DO UPDATE SET col = EXCLUDED.col, is_updated = true
RETURNING id,col,
CASE WHEN is_updated THEN 'UPDATED' ELSE 'INSERTED' END AS action;
<强> Rextester Demo 强>
输出:
╔════╦══════╦══════════╗
║ id ║ col ║ action ║
╠════╬══════╬══════════╣
║ 3 ║ c ║ INSERTED ║
║ 4 ║ d ║ INSERTED ║
║ 1 ║ aaaa ║ UPDATED ║
╚════╩══════╩══════════╝
答案 3 :(得分:2)
(xmax::text::bigint > 0)
或(NOT xmax = 0)
。一旦交易计数达到整数溢出,将转换为整数将中断。