PostgreSql INSERT 正在尝试使用现有的主键

PostgreSql INSERT is trying to use existing primary keys

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

首先,这是 table 的架构:

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;

table 有 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

这个 table 可能出了什么问题,如何纠正?我认为这可能与 table 之前使用 cascade 删除并重新输入数据有关,但我不确定这个理论。

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

所以,你必须改变你的顺序next_val

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

注:

To avoid blocking of concurrent transactions that obtain numbers from the same sequence, ALTER SEQUENCE's effects on the sequence generation parameters are never rolled back; those changes take effect immediately and are not reversible. However, the OWNED BY, OWNER TO, RENAME TO, and SET SCHEMA clauses cause ordinary catalog updates that can be rolled back.

ALTER SEQUENCE will not immediately affect nextval results in backends, other than the current one, that have preallocated (cached) sequence values. They will use up all cached values prior to noticing the changed sequence generation parameters. The current backend will be affected immediately.

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