UPSERT - INSERT ...在冲突中更新......
从版本 9.5 postgres 提供 UPSERT
功能与 INSERT
语句。
假设你有一个名为 my_table 的表,在之前的几个示例中创建。我们插入一行,返回插入行的 PK 值:
b=# INSERT INTO my_table (name,contact_number) values ('one',333) RETURNING id;
id 2
(1 row)
INSERT 0 1
现在,如果我们尝试使用现有唯一键插入行,则会引发异常:
b=# INSERT INTO my_table values (2,'one',333);
ERROR: duplicate key value violates unique constraint "my_table_pkey"
DETAIL: Key (id)=(2) already exists.
Upsert 功能提供了插入它的能力,解决冲突:
b=# INSERT INTO my_table values (2,'one',333) ON CONFLICT (id) DO UPDATE SET name = my_table.name||' changed to: "two" at '||now() returning *;
id | name | contact_number
----+-----------------------------------------------------------------------------------------------------------+----------------
2 | one changed to: "two" at 2016-11-23 08:32:17.105179+00 | 333
(1 row)
INSERT 0 1