我正在考虑使用PostgreSQL INSERT .. ON CONFLICT UPDATE
功能。理想情况下,我可以区分成功插入哪些行以及哪些行已更新。有办法吗?
答案 0 :(得分:2)
有一种方法可以不在表格中添加列:
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;
说明:
答案 1 :(得分:1)
您需要一个额外的辅助列(示例中为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)