为什么插入主键不影响顺序?
Why inserting primary key does not affect sequence?
插入带有隐式主键的行时,它似乎不影响主键顺序,然后,当尝试不使用 PK 插入时,它失败了:
create table testtable(
id serial primary key,
data integer not null
);
插入PK(例如数据迁移):
insert into testtable ( id, data ) values ( 1,2 ), ( 2,2 ), ( 3,2 ), ( 4,2 );
INSERT 0 4
正在插入新数据,没有 PK:
insert into testtable ( data ) values ( 4 ), ( 5 ), ( 6 ), ( 7 );
ERROR: duplicate key value violates unique constraint "testtable_pkey"
DETAIL: Key (id)=(1) already exists.
为什么第一个INSERT
之后的最大值没有设置顺序?我应该在使用 PK 插入后控制序列吗?有没有办法让sequence自动上正轨?
此行为的原因是在列的 DEFAULT
值中访问序列,显式插入列时未使用默认值。
我能想象到的实现你想要的唯一方法是有一个触发器在插入后修改序列,但我认为这将是一个缓慢而糟糕的解决方案。
继续的最佳方法是在完成迁移后调整一次顺序。
插入带有隐式主键的行时,它似乎不影响主键顺序,然后,当尝试不使用 PK 插入时,它失败了:
create table testtable(
id serial primary key,
data integer not null
);
插入PK(例如数据迁移):
insert into testtable ( id, data ) values ( 1,2 ), ( 2,2 ), ( 3,2 ), ( 4,2 );
INSERT 0 4
正在插入新数据,没有 PK:
insert into testtable ( data ) values ( 4 ), ( 5 ), ( 6 ), ( 7 );
ERROR: duplicate key value violates unique constraint "testtable_pkey"
DETAIL: Key (id)=(1) already exists.
为什么第一个INSERT
之后的最大值没有设置顺序?我应该在使用 PK 插入后控制序列吗?有没有办法让sequence自动上正轨?
此行为的原因是在列的 DEFAULT
值中访问序列,显式插入列时未使用默认值。
我能想象到的实现你想要的唯一方法是有一个触发器在插入后修改序列,但我认为这将是一个缓慢而糟糕的解决方案。
继续的最佳方法是在完成迁移后调整一次顺序。