确保唯一 ID 的 PostgreSQL 序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6046085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PostgreSQL sequence that ensure a unique ID
提问by Hectoret
Having a table with a columnn ID as primary key, and a column MyNumber that contains integers defined by the sequence myUniqueSequence. I would like to define myUniqueSequence in PostgreSQL that will return the next free and unique number for the column MyNumber.
有一个以列 ID 作为主键的表,以及一个包含由序列 myUniqueSequence 定义的整数的列 MyNumber。我想在 PostgreSQL 中定义 myUniqueSequence,它将返回 MyNumber 列的下一个自由和唯一编号。
This means, the next time a new row is created programatically will start by number 1, if it's free it will use it for the column myNumber, if not, it tries with 2 and so on.
这意味着,下次以编程方式创建新行时,将从编号 1 开始,如果空闲,它将用于 myNumber 列,如果没有,则尝试使用 2,依此类推。
回答by Lukas Eder
Use the serial
data type for your column (instead of your own sequence):
使用serial
列的数据类型(而不是您自己的序列):
http://www.postgresql.org/docs/9.0/static/datatype-numeric.html#DATATYPE-SERIAL
http://www.postgresql.org/docs/9.0/static/datatype-numeric.html#DATATYPE-SERIAL