如何在 PostgreSQL 中自动递增?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3108777/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:35:26  来源:igfitidea点击:

How to auto-increment in PostgreSQL?

postgresql

提问by Sanjay Kumar

I have a table Login. It has the fields rank, username and password.

我有一个表登录。它有字段等级、用户名和密码。

I want the rank field value to be auto incremented with respect to addition of username and password.

我希望排名字段值相对于用户名和密码的添加自动递增。

How do I do this in PostgreSQL ?

我如何在 PostgreSQL 中做到这一点?

回答by pyrocumulus

You are looking for a column with datatype Serial. See this page(bottom) for more information about that datatype.

您正在寻找数据类型为 的列Serial。有关数据类型的更多信息,请参阅此页面(底部)。

So for example, your table definition could look like this:

例如,您的表定义可能如下所示:

CREATE TABLE yourtable (
    rank SERIAL NOT NULL,
    username VARCHAR(20) NOT NULL,
    password VARCHAR(50) NOT NULL
);

回答by Sanjay Kumar

A Sequence can be created which will auto increment the value of rank column.

可以创建一个序列,它会自动增加排名列的值。

CREATE SEQUENCE rank_id_seq;

CREATE TABLE yourtable (
    rank INTEGER NOT NULL default nextval('rank_id_seq'),
    username VARCHAR(20) NOT NULL,
    password VARCHAR(50) NOT NULL
);

ALTER SEQUENCE rank_id_seq owned by yourtable.rank;

回答by Timothy

create table login (rank serial, username varchar(20), password varchar(20))

Serial datatype is what you want.

串行数据类型是您想要的。