如何修复 Postgres 9+ 中的重复键值违反唯一约束错误
How to fix duplicate key value violates unique constraint error in Postges 9+
有时会出现奇怪的重复键错误
duplicate key value violates unique constraint "session_pkey"
Key (workplace)=(WIN-N9BSKUNKBC8 ) already exists.
出现在脚本中:
delete from session where workplace='WIN-N9BSKUNKBC8' ;
INSERT INTO session (workplace,ipaddress,logintime,loggeduser)
SELECT 'WIN-N9BSKUNKBC8' , inet_client_addr()::CHAR(14),current_timestamp::CHAR(28),CURRENT_USER WHERE NOT EXISTS (SELECT 1 FROM session WHERE workplace='WIN-N9BSKUNKBC8' )
Sript 是每 10 分钟 运行 形式的 windows 任务计划程序。错误只是偶尔发生。
如何解决这个问题?
Table 定义为
CREATE TABLE public.session
(
loggeduser character(10) ,
workplace character(16) NOT NULL,
ipaddress character(20) ,
logintime character(28) ,
activity timestamp with time zone,
CONSTRAINT session_pkey PRIMARY KEY (workplace)
)
环境:
PostgreSQL 13.1, compiled by Visual C++ build 1914, 64-bit
Windows server 2019
psqlODBC driver 13.00.0000
您可以使用 on conflict
:
INSERT INTO session (workplace,ipaddress,logintime,loggeduser)
SELECT 'WIN-N9BSKUNKBC8',
inet_client_addr()::CHAR(14),current_timestamp::CHAR(28),
CURRENT_USER
ON CONFLICT DO NOTHING;
鉴于您只有一行,我的猜测是问题是由于并发问题造成的。
有时会出现奇怪的重复键错误
duplicate key value violates unique constraint "session_pkey"
Key (workplace)=(WIN-N9BSKUNKBC8 ) already exists.
出现在脚本中:
delete from session where workplace='WIN-N9BSKUNKBC8' ;
INSERT INTO session (workplace,ipaddress,logintime,loggeduser)
SELECT 'WIN-N9BSKUNKBC8' , inet_client_addr()::CHAR(14),current_timestamp::CHAR(28),CURRENT_USER WHERE NOT EXISTS (SELECT 1 FROM session WHERE workplace='WIN-N9BSKUNKBC8' )
Sript 是每 10 分钟 运行 形式的 windows 任务计划程序。错误只是偶尔发生。
如何解决这个问题? Table 定义为
CREATE TABLE public.session
(
loggeduser character(10) ,
workplace character(16) NOT NULL,
ipaddress character(20) ,
logintime character(28) ,
activity timestamp with time zone,
CONSTRAINT session_pkey PRIMARY KEY (workplace)
)
环境:
PostgreSQL 13.1, compiled by Visual C++ build 1914, 64-bit
Windows server 2019
psqlODBC driver 13.00.0000
您可以使用 on conflict
:
INSERT INTO session (workplace,ipaddress,logintime,loggeduser)
SELECT 'WIN-N9BSKUNKBC8',
inet_client_addr()::CHAR(14),current_timestamp::CHAR(28),
CURRENT_USER
ON CONFLICT DO NOTHING;
鉴于您只有一行,我的猜测是问题是由于并发问题造成的。