我有下表:
CREATE TABLE api.capabilities (
id uuid NOT NULL,
historycounter int8 NOT NULL DEFAULT 0,
url jsonb NOT NULL,
checkservice bool NOT NULL DEFAULT false,
added timestamptz NOT NULL,
modified timestamptz NULL,
deleted timestamptz NULL,
adduser varchar(40) NOT NULL DEFAULT 'pgsql'::character varying,
lastuser varchar(40) NULL,
CONSTRAINT id_histcount PRIMARY KEY (id, historycounter)
);有以下内容:
|80af3ff3-2dc1-434b-ad3c-490d8b4a7949|1|{"host":"dev.33wessling824.net","protocol":“http”}false false 2022-07-12 18:35:17.465 +0200区pgsql
|80af3ff3-2dc1-434b-ad3c-490d8b4a7949|0|{"host":"dev.33wessling824.net",“协议”:“http”{##**$$}{##**$$}2022-07-12 18:35:17.465 +0200 2022-07-14 11:46:50.073 +0200维斯林
我想运行以下更新语句:
Update api.capabilities set historycounter = historycounter + 1 where id = '80af3ff3-2dc1-434b-ad3c-490d8b4a7949';尝试此操作会导致错误duplicate key value violates unique constraint "id_histcount"。
因为首先更新了带有historycounter = 0的dataset,所以我确实得到了这个错误。如何更改我的代码,以便首次使用最大的历史计数器更新数据集?
提前感谢!阿奇姆
发布于 2022-07-14 12:42:25
如果您完全确定您的数据不会在您的事务后违反主键。首先,alter约束。这是安全的:
ALTER TABLE api.capabilities
ALTER CONSTRAINT id_histcount DEFERRABLE INITIALLY IMMEDIATE;然后在你的交易中:
begin transaction;
set constraints all deferred;
Update api.capabilities set historycounter = historycounter + 1 where id = '80af3ff3-2dc1-434b-ad3c-490d8b4a7949';
--your other operations
commit transaction;来源:https://www.postgresql.org/docs/current/sql-set-constraints.html
https://stackoverflow.com/questions/72980530
复制相似问题