为什么 SERIAL 不能在 Postgres 中处理这个简单的 table?
Why SERIAL is not working on this simple table in Postgres?
我正在使用 Postgres 9.1。 auto_increment(串行)不工作。我刚发现关于 'serial' 的内容:
https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL
CREATE TYPE FAMILY AS(
id int,
name VARCHAR(35),
img_address VARCHAR(150));
CREATE TABLE FAMILIES of FAMILY(
id SERIAL primary key NOT NULL,
name NOT NULL
);
ERROR: syntax error at or near "SERIAL"
LINE 7: id SERIAL primary key NOT NULL,
^
********** Error **********
ERROR: syntax error at or near "SERIAL"
SQL state: 42601
当您使用以下语法创建 table 时:
CREATE TABLE xxx OF yyyy
您可以添加默认值和约束,但不能更改或指定列的类型。
SERIAL 类型实际上是数据类型、NOT NULL 约束和默认值规范的组合。相当于:
integer NOT NULL DEFAULT nextval('tablename_colname_seq')
因此,您必须使用:
CREATE SEQUENCE families_id_seq;
CREATE TABLE FAMILIES of FAMILY(
id WITH OPTIONS NOT NULL DEFAULT nextval('families_id_seq'),
name WITH OPTIONS NOT NULL
);
ALTER SEQUENCE families_id_seq OWNED BY FAMILIES.id;
您还必须手动创建序列 families_id_seq
,如上所示。
我正在使用 Postgres 9.1。 auto_increment(串行)不工作。我刚发现关于 'serial' 的内容: https://www.postgresql.org/docs/current/static/datatype-numeric.html#DATATYPE-SERIAL
CREATE TYPE FAMILY AS(
id int,
name VARCHAR(35),
img_address VARCHAR(150));
CREATE TABLE FAMILIES of FAMILY(
id SERIAL primary key NOT NULL,
name NOT NULL
);
ERROR: syntax error at or near "SERIAL"
LINE 7: id SERIAL primary key NOT NULL,
^
********** Error **********
ERROR: syntax error at or near "SERIAL"
SQL state: 42601
当您使用以下语法创建 table 时:
CREATE TABLE xxx OF yyyy
您可以添加默认值和约束,但不能更改或指定列的类型。
SERIAL 类型实际上是数据类型、NOT NULL 约束和默认值规范的组合。相当于:
integer NOT NULL DEFAULT nextval('tablename_colname_seq')
因此,您必须使用:
CREATE SEQUENCE families_id_seq;
CREATE TABLE FAMILIES of FAMILY(
id WITH OPTIONS NOT NULL DEFAULT nextval('families_id_seq'),
name WITH OPTIONS NOT NULL
);
ALTER SEQUENCE families_id_seq OWNED BY FAMILIES.id;
您还必须手动创建序列 families_id_seq
,如上所示。