【发布时间】:2023-02-04 01:57:01
【问题描述】:
我一直在尝试使用 PostgreSQL upsert 来更新值,以防此类行已经存在。在我的用例中,新值很可能与现有值完全相同,所以我想确保不会执行任何更新(也就是说 - 不会创建具有更高 xmax 版本的新行)如果值是相同的。我试过为此使用 IS DISTINCT FROM 子句,虽然它在常规更新语句中按预期工作(xmax 对于无效的更新保持不变),但在 upsert 表达式中使用时它似乎仍然会创建新行.
请考虑以下示例:
- 创建测试表:
create table upsert_test (id integer, name text, primary key (id));- 插入行并获取其
xmax版本:
insert into upsert_test (id, name) values (1, 'hello'); select *, xmax from upsert_test;- 执行无效的更新。观察
xmax在每次执行时(意外地)递增:
insert into upsert_test (id, name) values (1, 'hello') on conflict on constraint upsert_test_pkey do update set name = excluded.name where upsert_test is distinct from excluded; select *, xmax from upsert_test ;这是预期的行为吗?有没有办法阻止 PostgreSQL 为这种情况创建新行?
- 插入行并获取其
【问题讨论】:
-
xmax是最高的完成交易ID,所以每次交易后修改是绝对正常的...xmax不是表upsert_test的数据的一部分
标签: sql postgresql upsert