在我的 postgres 数据库中有一个名为
testing_thing
的表,我可以看到它(通过在我的 psql 提示符中运行 \d testing_thing
)它被定义为
Table "public.testing_thing"
Column | Type | Collation | Nullable | Default
--------------+-------------------+-----------+----------+-----------------------------------------------------
thing_id | integer | | not null | nextval('testing_thing_thing_id_seq'::regclass)
thing_num | smallint | | not null | 0
thing_desc | character varying | | not null |
Indexes:
"testing_thing_pk" PRIMARY KEY, btree (thing_num)
我想删除它并按原样重新创建它,但我不知道如何重现
nextval('testing_thing_thing_id_seq'::regclass)
列
thing_id
的部分。
这是我用来创建表的查询:
CREATE TABLE testing_thing(
thing_id integer NOT NULL, --what else should I put here?
thing_num smallint NOT NULL PRIMARY KEY DEFAULT 0,
thing_desc varchar(100) NOT NULL
);
缺少什么?
将
DEFAULT
添加到要递增的列并调用 nextval()
:
CREATE SEQUENCE testing_thing_thing_id_seq START WITH 1;
CREATE TABLE testing_thing(
thing_id integer NOT NULL DEFAULT nextval('testing_thing_thing_id_seq'),
thing_num smallint NOT NULL PRIMARY KEY DEFAULT 0,
thing_desc varchar(100) NOT NULL
);
旁注:请记住,将序列附加到列并不会阻止用户手动用随机数据填充它,这可能会导致主键出现真正令人讨厌的问题。如果您想克服它并且不一定需要序列,请考虑创建一个标识列,例如
CREATE TABLE testing_thing(
thing_id integer NOT NULL GENERATED ALWAYS AS IDENTITY,
thing_num smallint NOT NULL PRIMARY KEY DEFAULT 0,
thing_desc varchar(100) NOT NULL
);
db<>fiddle
CREATE TABLE testing_thing(
thing_id integer NOT NULL ,
thing_num smallint NOT NULL PRIMARY KEY DEFAULT 0,
thing_desc varchar(100) NOT NULL
);
CREATE SEQUENCE IF NOT EXISTS testing_thing_thing_id_seq
INCREMENT 1
START 1
MINVALUE 1
MAXVALUE 100
CACHE 1
OWNED BY testing_thing.thing_id;
ALTER TABLE testing_thing
ALTER COLUMN thing_id SET DEFAULT nextval('testing_thing_thing_id_seq'::regclass);