[英]I don't understand how postgresql's nextval() work, can someone explain?
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.我正在使用 postgreSQL,但似乎无法理解 nextval() 函数。 I read this, but it's not clear to me.我读过这个,但我不清楚。 http://www.postgresql.org/docs/current/interactive/functions-sequence.html what are the benefits/use cases for nexval()? http://www.postgresql.org/docs/current/interactive/functions-sequence.html nexval() 的好处/用例是什么?
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
下阅读文档中的CYCLE
)。
So you can be sure all the values of your primary keys will be generated unique within the table.因此,您可以确保主键的所有值都将在表中生成唯一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.