PostgreSQL INSERT试图使用现有的主键

时间:2018-11-01 07:49:00

标签: postgresql postgresql-9.1 cascade insert-into

我在使用Postgres表时遇到一个特殊的问题。当我尝试执行简单的INSERT时,它返回错误-duplicate key value violates unique constraint

对于初学者来说,这是表的架构:

CREATE TABLE app.guardians
(
  guardian_id serial NOT NULL,
  first_name character varying NOT NULL,
  middle_name character varying,
  last_name character varying NOT NULL,
  id_number character varying NOT NULL,
  telephone character varying,
  email character varying,
  creation_date timestamp without time zone NOT NULL DEFAULT now(),
  created_by integer,
  active boolean NOT NULL DEFAULT true,
  occupation character varying,
  address character varying,
  marital_status character varying,
  modified_date timestamp without time zone,
  modified_by integer,
  CONSTRAINT "PK_guardian_id" PRIMARY KEY (guardian_id ),
  CONSTRAINT "U_id_number" UNIQUE (id_number )
)
WITH (
  OIDS=FALSE
);
ALTER TABLE app.guardians
  OWNER TO postgres;

该表有400行。现在,假设我尝试执行此简单的INSERT

INSERT INTO app.guardians(first_name, last_name, id_number) VALUES('This', 'Fails', '123456');

我得到了错误:

ERROR:  duplicate key value violates unique constraint "PK_guardian_id"
DETAIL:  Key (guardian_id)=(2) already exists.

如果我再次尝试运行相同的查询,则错误消息的详细信息将为:

DETAIL:  Key (guardian_id)=(3) already exists.

DETAIL:  Key (guardian_id)=(4) already exists.

递增,直到到达不存在的guardian_id

在此特定表上可能出了什么问题,该如何纠正?我认为这可能与以下事实有关:早先使用cascade删除了表,并重新输入了数据,但是我不确定该理论。

1 个答案:

答案 0 :(得分:1)

此错误的原因是您的next_val序列不正确。手动插入具有自动增量的字段时会发生这种情况

因此,您必须更改next_val的顺序

alter sequence "PK_guardian_id"
start with (
   select max(quardian_id) + 1 
   from app.guardians
)

注意:

  

为避免阻塞从同一序列中获取数字的并发事务,永远不会回滚ALTER SEQUENCE对序列生成参数的影响。这些更改将立即生效,并且不可逆。但是,OWNED BY,OWNER TO,RENAME TO和SET SCHEMA子句会导致可以回滚的普通目录更新。

     

ALTER SEQUENCE不会立即影响后端(当前后端除外)中具有预分配(缓存)序列值的nextval结果。在注意到更改的序列生成参数之前,它们将用尽所有缓存的值。当前的后端将立即受到影响。

文档: https://www.postgresql.org/docs/9.6/static/sql-altersequence.html