SQL PostgreSQL 9.1 主键自增
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20781111/
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 9.1 primary key autoincrement
提问by WildDev
I'm trying to add a primary key with an autoincrement.
我正在尝试使用自动增量添加主键。
I have read some docs and other questions - there're SERIAL
and nextval()
statements but it doesn't work.
我已经阅读了一些文档和其他问题 - 有SERIAL
和nextval()
陈述,但它不起作用。
Here's what I made:
这是我做的:
CREATE TABLE IF NOT EXISTS "category" (
"id" integer SERIAL PRIMARY KEY,
"name" varchar(30) DEFAULT NULL
); // the error near "SERIAL"
and
和
CREATE SEQUENCE your_seq;
CREATE TABLE IF NOT EXISTS "category" (
"id" integer PRIMARY KEY nextval('your_seq'),
"name" varchar(30) DEFAULT NULL
); // the error near 'nextval'
What do I wrong? I just want to increment the primary key by 1.
我怎么了?我只想将主键加 1。
回答by mu is too short
serial
is, more or less, a column type so saying integer serial
is like saying text text
, just say serial
:
serial
或多或少是一种列类型,所以说integer serial
就像说text text
,只需说serial
:
CREATE TABLE IF NOT EXISTS "category" (
"id" SERIAL PRIMARY KEY,
"name" varchar(30) DEFAULT NULL
);
If you want to create the sequence yourself then you want to make the default value of id
the next value in the sequence and that means saying default nextval('your_seq')
:
如果您想自己创建序列,那么您希望将序列中id
的下一个值设为默认值,这意味着default nextval('your_seq')
:
CREATE SEQUENCE your_seq;
CREATE TABLE IF NOT EXISTS "category" (
"id" integer PRIMARY KEY default nextval('your_seq'),
"name" varchar(30) DEFAULT NULL
);
To simulate the usual serial
behavior you'll also want to make the sequence owned by the table:
要模拟通常的serial
行为,您还需要使表拥有序列:
alter sequence your_seq owned by category.id;
Reading the Serial Typessection of the manual might be fruitful.
阅读手册的串行类型部分可能会很有成效。
I'd also recommend that you don't double quote your table and column names unless you have to. PostgreSQL will fold your identifiers to lower case so id
and "id"
will be the same thing but unnecessary quoting is a bad habit that can easily lead to a big mess of quotes everywhere.
我还建议你不要双引号你的表和列名,除非你必须。PostgreSQL将折叠的标识符以小写因此id
而"id"
将是相同的事情,但不必要的报价是一个坏习惯,很容易导致行情的大混乱无处不在。
回答by Valentin Podkamennyi
If someone needs to modify an existing table to add a primary key with auto-increment:
如果有人需要修改现有表以添加具有自动增量的主键:
ALTER TABLE table_name ADD COLUMN pk_column_name SERIAL PRIMARY KEY;