SQL postgresql nextval()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36782006/
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 nextval()
提问by devdropper87
I'm just starting to wade into backend development after my first few months on the job as a front end dev. I'm working with postgreSQL and can't seem to wrap my head around the nextval() function. I read this, but it's not clear to me. http://www.postgresql.org/docs/current/interactive/functions-sequence.htmlwhat are the benefits/use cases for nexval()?
在我担任前端开发人员的头几个月后,我才刚刚开始涉足后端开发。我正在使用 postgreSQL,但似乎无法理解 nextval() 函数。我读过这个,但我不清楚。 http://www.postgresql.org/docs/current/interactive/functions-sequence.htmlnexval() 的好处/用例是什么?
回答by Quassnoi
NEXTVAL
is a function to get the next value from a sequence.
NEXTVAL
是从序列中获取下一个值的函数。
Sequence is an object which returns ever-increasing numbers, different for each call, regardless of transactions etc.
Sequence 是一个对象,它返回不断增加的数字,每次调用都不同,而不管交易等如何。
Each time you call NEXTVAL
, you get a different number.
每次拨打NEXTVAL
,您都会得到不同的号码。
This is mainly used to generate surrogate primary keys for you tables.
这主要用于为您的表生成代理主键。
You can create a table like this:
您可以像这样创建一个表:
CREATE SEQUENCE mysequence;
CREATE TABLE mytable (id BIGINT NOT NULL PRIMARY KEY, value INT);
and insert values like this:
并插入这样的值:
INSERT
INTO mytable (id, value)
VALUES
(NEXTVAL('mysequence'), 1),
(NEXTVAL('mysequence'), 2);
and see what you get:
看看你得到了什么:
SELECT * FROM mytable;
id | value
----+-------
1 | 1
2 | 2
PostgreSQL offers a nice syntax sugar for this:
PostgreSQL 为此提供了一个很好的语法糖:
CREATE TABLE mytable (id BIGSERIAL PRIMARY KEY, value INT);
which is equivalent to
这相当于
CREATE SEQUENCE mytable_id_seq; -- table_column_'seq'
CREATE TABLE mytable (id BIGINT NOT NULL PRIMARY KEY DEFAULT NEXTVAL('mytable_id_seq'), value INT); -- it's not null and has a default value automatically
and can be used like this:
并且可以这样使用:
INSERT
INTO mytable (value)
VALUES (1),
(2); -- you can omit id, it will get filled for you.
Note that even if you rollback your insert statement or run concurrent statements from two different sessions, the returned sequence values will never be the same and never get reused (read the fine print in the docs though under CYCLE
).
请注意,即使您回滚插入语句或从两个不同的会话运行并发语句,返回的序列值也永远不会相同并且永远不会被重用(尽管在 下阅读文档中的细则CYCLE
)。
So you can be sure all the values of your primary keys will be generated unique within the table.
因此,您可以确保主键的所有值都将在表中生成唯一。