PostgreSQL INSERT ON CONFLICT UPDATE (upsert) 使用所有排除的值

PostgreSQL INSERT ON CONFLICT UPDATE (upsert) use all excluded values

当你更新一行(PostgreSQL >= 9.5),并且你希望可能的 INSERT 与可能的 UPDATE 完全相同,你可以这样写:

INSERT INTO tablename (id, username, password, level, email) 
                VALUES (1, 'John', 'qwerty', 5, 'john@mail.com') 
ON CONFLICT (id) DO UPDATE SET 
  id=EXCLUDED.id, username=EXCLUDED.username,
  password=EXCLUDED.password, level=EXCLUDED.level,email=EXCLUDED.email

有更短的路吗?只是说:使用所有 EXCLUDE 值。

我以前在 SQLite 中这样做:

INSERT OR REPLACE INTO tablename (id, user, password, level, email) 
                        VALUES (1, 'John', 'qwerty', 5, 'john@mail.com')

Postgres 尚未实现与 INSERT OR REPLACE 等效的功能。来自 ON CONFLICT docs(强调我的):

It can be either DO NOTHING, or a DO UPDATE clause specifying the exact details of the UPDATE action to be performed in case of a conflict.

虽然它不会为您提供 shorthand 替换,但 ON CONFLICT DO UPDATE 更普遍,因为它允许您根据预先存在的数据设置新值。例如:

INSERT INTO users (id, level)
VALUES (1, 0)
ON CONFLICT (id) DO UPDATE
SET level = users.level + 1;