Postgresql 为什么插入主键不影响序列?
插入带有隐式主键的行时,它似乎不会影响主键顺序,然后,尝试在没有PK的情况下插入时,失败:Postgresql 为什么插入主键不影响序列?,postgresql,primary-key,postgresql-9.5,Postgresql,Primary Key,Postgresql 9.5,插入带有隐式主键的行时,它似乎不会影响主键顺序,然后,尝试在没有PK的情况下插入时,失败: create table testtable( id serial primary key, data integer not null ); 使用PK插入(例如在数据迁移时): 插入新数据,无主键: insert into testtable ( data ) values ( 4 ), ( 5 ), ( 6 ), ( 7 ); ERROR: duplicate key value viol
create table testtable(
id serial primary key,
data integer not null
);
使用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.
为什么不在首次插入后的最大值上设置顺序?我应该在插入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.