gpt4 book ai didi

sql - Postgresql:SERIAL 在约束 INSERT 失败时递增

转载 作者:行者123 更新时间:2023-11-29 11:16:39 26 4
gpt4 key购买 nike

有一个像这样的简单表结构:

CREATE TABLE test (
id INT PRIMARY KEY,
sid SERIAL
);

我注意到如果我尝试插入一行但它未通过约束测试(即 PRIMARY KEY 约束),SERIAL 计数器无论如何都会递增,因此下一次成功插入时,sid 将是 sid + 2 而不是 sid + 1

这是正常行为吗?有什么办法可以防止这种情况?

最佳答案

是的,这是设计使然。 Serial 数据类型使用序列,文档中描述了此行为 (Sequence Manipulation Functions):

To avoid blocking concurrent transactions that obtain numbers from the same sequence, a nextval operation is never rolled back; that is, once a value has been fetched it is considered used, even if the transaction that did the nextval later aborts. This means that aborted transactions might leave unused "holes" in the sequence of assigned values.

没有办法有效地防止它。但是,您可以通过创建单行表并在获取下一个值时锁定它来开发自己的序列。

关于sql - Postgresql:SERIAL 在约束 INSERT 失败时递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35849944/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com