问题
I'm thinking of using PostgreSQL INSERT .. ON CONFLICT UPDATE
functionality. Ideally I would be able to distinguish between which rows were successful inserted and which were updated. Is there a way to do it?
回答1:
You need an additional auxiliary column for this (updated
in the example).
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)
回答2:
There is a way without adding a column to your table:
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;
Explanation:
- Detect if the row was updated or inserted
来源:https://stackoverflow.com/questions/38613887/postgres-upsert-distinguish-between-new-and-updated-rows