postgresql Postgres upsert:区分新行和更新行[重复]

hlswsv35  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(2)|浏览(170)

此问题已在此处有答案

Detect if the row was updated or inserted(1个答案)
How to use RETURNING with ON CONFLICT in PostgreSQL?(10个答案)
Differentiate inserted and updated rows in UPSERT using system columns(1个答案)
3年前关闭。
我正在考虑使用PostgreSQL INSERT .. ON CONFLICT UPDATE功能。理想情况下,我应该能够区分哪些行被成功插入,哪些行被更新。有办法吗?

vd2z7a6w

vd2z7a6w1#

有一种方法不需要在表中添加列:

CREATE TABLE tbl(id int PRIMARY KEY, col int);
INSERT INTO tbl VALUES (1, 1);
INSERT INTO tbl(id, col)
VALUES (1,11), (2,22)
ON     CONFLICT (id) DO UPDATE
SET    col = EXCLUDED.col
RETURNING *, (xmax = 0) AS inserted;

说明:

  • 检测行是否已更新或插入

由于并发写加载下的争用条件,可能不会返回某些行。参见:

  • 如何在PostgreSQL中使用RETURNING with ON CONFLICT?
g2ieeal7

g2ieeal72#

您需要一个额外的辅助列(示例中的updated)。

create table test (id int primary key, str text, updated boolean);
insert into test values (1, 'old', false);

insert into test values
    (1, 'new 1', false),
    (2, 'new 2', false)
on conflict (id) do
update set 
    str = excluded.str, updated = true
returning *;

 id |  str  | updated 
----+-------+---------
  1 | new 1 | t
  2 | new 2 | f
(2 rows)

相关问题