我想在这里实现upsert。某些列中的值将在每次插入时更新。
我用的是-
insert into deployment.nodes values('sind','11', now(),'temp','not-active')
on conflict on constraint nodes_pkey
DO UPDATE SET latest=now(), agent='na', status='active';表如下:
create table if not exists deployment.nodes (
account varchar(40),
hostname varchar(100),
latest timestamptz,
agent varchar(50),
status varchar(50),
primary key(account,hostname,agent)
);在两次/三次插入后,我得到-
devops=# insert into deployment.nodes values('sind','11', now(),'temp','not-active') on conflict on constraint nodes_pkey DO UPDATE SET latest=now(), agent='ne', status='active';
INSERT 0 1
devops=# insert into deployment.nodes values('sind','11', now(),'temp','not-active') on conflict on constraint nodes_pkey DO UPDATE SET latest=now(), agent='ne', status='active';
INSERT 0 1
devops=# insert into deployment.nodes values('sind','11', now(),'temp','not-active') on conflict on constraint nodes_pkey DO UPDATE SET latest=now(), agent='ne', status='active';
INSERT 0 1
devops=# insert into deployment.nodes values('sind','11', now(),'temp','not-active') on conflict on constraint nodes_pkey DO UPDATE SET latest=now(), agent='ne', status='active';
ERROR: duplicate key value violates unique constraint "nodes_pkey"
DETAIL: Key (account, hostname, agent)=(sind, 11, ne) already exists.Postgres版本-
devops=# SHOW server_version;
server_version
----------------
10.11知道发生了什么吗?
发布于 2020-03-27 17:27:49
这是正常行为。第一次插入时插入了代理temp。第二次插入尝试将第一条记录更新为代理ne。第三个尝试在新记录中再次插入代理temp,第四个尝试将temp更新为代理ne,从而导致与第一个记录的冲突。
诚挚的问候,
比亚尔尼
发布于 2020-03-27 20:07:29
感谢@Bjarni澄清这一点。
冲突时更新应该更新引起冲突的行。在我的例子中,冲突解决程序本身似乎有一个冲突。
我在"insert语句“和”冲突语句“中使用了相同的主键值,这就解决了这个问题。
insert into deployment.nodes
values('sind','11', now(),'temp','not-active')
on conflict on constraint nodes_pkey
DO UPDATE SET latest=now(), agent='temp', status='active';谢谢!
https://stackoverflow.com/questions/60882840
复制相似问题