java 无法在PostgreSQL中设置序列的起始值

ffx8fchx  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(126)

我正在Sping Boot 应用程序中使用迁移脚本,并创建如下所示的序列:

CREATE SEQUENCE IF NOT EXISTS public.sequence_user START WITH 4 INCREMENT BY 5;

然后,在另一个迁移文件中,我通过以下脚本插入3个用户:

INSERT INTO public.user (id, first_name, last_name, username, "password")
VALUES (1, 'John', 'Doe', 'johndoe', '...');
INSERT INTO public.user (id, first_name, last_name, username, "password")
VALUES (2, 'Frank', 'James', 'frank', '...');
INSERT INTO public.user (id, first_name, last_name, username, "password")
VALUES (3, 'Foo', 'Bar', 'foo', '...');

ALTER SEQUENCE sequence_user RESTART;
UPDATE public.user SET id = DEFAULT;

但是,当我运行应用并尝试添加新用户时,此用户ID先取0,然后取1,这会引发错误。那么,我如何才能使此序列从4开始给予数字呢?

**更新:**创建表语句:

CREATE SEQUENCE IF NOT EXISTS public.sequence_user START WITH 1 INCREMENT BY 5;

CREATE TABLE public."user"
(
    id         BIGINT       NOT NULL,
    first_name VARCHAR(50)  NOT NULL,
    last_name  VARCHAR(50)  NOT NULL,
    username   VARCHAR(20)  NOT NULL,
    password   VARCHAR(100) NOT NULL,
    CONSTRAINT pk_user PRIMARY KEY (id)
);
jmo0nnb3

jmo0nnb31#

要将序列移动到任意位置,可以使用setval()

select setval('public.sequence_user',
              (select max(id) from public.user) );

请注意,INCREMENT BY 5表示序列将始终以5为步长向前移动。您也可以将序列正确链接到列:

alter sequence public.sequence_user owned by public.user.id;
alter table public.user 
   alter column id 
   set default nextval('public.sequence_user');
select setval(pg_get_serial_sequence('public.user','id'),
              (select max(id) from public.user) );

最好让db创建、处理和维护您的id序列:

create table public.user (
   id int generated by default as identity primary key, 
   first_name text, 
   last_name  text, 
   username   text, 
   "password" text);

select pg_get_serial_sequence('public.user','id');--public.user_id_seq

在这两种情况下,序列都成为默认值的生成器,但仍然允许您插入自己的行,只要您在以后让它知道:demo

insert into public.user (id, first_name, last_name, username, "password")
values 
  (1, 'John', 'Doe', 'johndoe', '...')
, (2, 'Frank', 'James', 'frank', '...')
, (3, 'Foo', 'Bar', 'foo', '...');

select setval(pg_get_serial_sequence('public.user','id'),
              (select max(id) from public.user) );

insert into public.user (id, first_name, last_name, username, "password")
values (default, 'Adam', 'Savage', 'adamsavage', '...');

insert into public.user (first_name, last_name, username, "password")
values ('Adam', 'Sandler', 'adamsandler', '...');

相关问题