我从MySQL切换到PostgreSQL,我想知道我如何能有一个INT列与自动递增。我在PostgreSQL文档中看到了一个名为SERIAL的数据类型,但我在使用它时遇到了语法错误。
当前回答
从Postgres 10开始,也支持SQL标准定义的标识列:
create table foo
(
id integer generated always as identity
);
创建除非明确要求否则不能重写的标识列。下面的插入将失败,因为总是生成一个列:
insert into foo (id)
values (1);
然而,这可以被否决:
insert into foo (id) overriding system value
values (1);
当使用默认生成的选项时,这本质上与现有的串行实现相同:
create table foo
(
id integer generated by default as identity
);
当手动提供值时,底层序列也需要手动调整—与串行列相同。
默认情况下,标识列不是主键(就像串行列一样)。如果应该是一个,则需要手动定义主键约束。
其他回答
从Postgres 10开始,也支持SQL标准定义的标识列:
create table foo
(
id integer generated always as identity
);
创建除非明确要求否则不能重写的标识列。下面的插入将失败,因为总是生成一个列:
insert into foo (id)
values (1);
然而,这可以被否决:
insert into foo (id) overriding system value
values (1);
当使用默认生成的选项时,这本质上与现有的串行实现相同:
create table foo
(
id integer generated by default as identity
);
当手动提供值时,底层序列也需要手动调整—与串行列相同。
默认情况下,标识列不是主键(就像串行列一样)。如果应该是一个,则需要手动定义主键约束。
在所问问题的上下文中以及@sereja1c对注释的回复中,创建SERIAL隐式地创建序列,因此对于上面的示例-
CREATE TABLE foo (id SERIAL,bar varchar);
CREATE TABLE将隐式地为序列列foo.id创建序列foo_id_seq。因此,SERIAL[4字节]很容易使用,除非您的id需要特定的数据类型。
如果你想在已经存在的表中添加sequence到id,你可以使用:
CREATE SEQUENCE user_id_seq;
ALTER TABLE user ALTER user_id SET DEFAULT NEXTVAL('user_id_seq');
你必须小心不要直接插入到你的SERIAL或sequence字段中,否则当序列达到插入值时,你的写入将失败:
-- Table: "test"
-- DROP TABLE test;
CREATE TABLE test
(
"ID" SERIAL,
"Rank" integer NOT NULL,
"GermanHeadword" "text" [] NOT NULL,
"PartOfSpeech" "text" NOT NULL,
"ExampleSentence" "text" NOT NULL,
"EnglishGloss" "text"[] NOT NULL,
CONSTRAINT "PKey" PRIMARY KEY ("ID", "Rank")
)
WITH (
OIDS=FALSE
);
-- ALTER TABLE test OWNER TO postgres;
INSERT INTO test("Rank", "GermanHeadword", "PartOfSpeech", "ExampleSentence", "EnglishGloss")
VALUES (1, '{"der", "die", "das", "den", "dem", "des"}', 'art', 'Der Mann küsst die Frau und das Kind schaut zu', '{"the", "of the" }');
INSERT INTO test("ID", "Rank", "GermanHeadword", "PartOfSpeech", "ExampleSentence", "EnglishGloss")
VALUES (2, 1, '{"der", "die", "das"}', 'pron', 'Das ist mein Fahrrad', '{"that", "those"}');
INSERT INTO test("Rank", "GermanHeadword", "PartOfSpeech", "ExampleSentence", "EnglishGloss")
VALUES (1, '{"der", "die", "das"}', 'pron', 'Die Frau, die nebenen wohnt, heißt Renate', '{"that", "who"}');
SELECT * from test;
自从PostgreSQL 10
CREATE TABLE test_new (
id int GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
payload text
);
推荐文章
- 将varchar字段的类型更改为整数:"不能自动转换为整数类型"
- PostgreSQL可以索引数组列吗?
- PostgreSQL:角色不允许登录
- 如何查找Postgres / PostgreSQL表及其索引的磁盘大小
- 是使用各有一个模式的多个数据库更好,还是使用一个数据库有多个模式更好?
- 如果字符串包含
- 对于PostgreSQL表来说,多大才算太大?
- 将一列的多个结果行连接为一列,按另一列分组
- 使用pgadmin连接到heroku数据库
- 在PostgreSQL中快速发现表的行数
- 更改varchar列的大小为较低的长度
- 如何首次配置postgresql ?
- 数据库性能调优有哪些资源?
- 如何在PostgreSQL中自动更新时间戳
- 当使用JDBC连接到postgres时,是否可以指定模式?