如何在 postgres table "testing_thing" 中将 "nextval('testing_thing_thing_id_seq'::regclass)" 声明为列 "thing_id" 的默认值?

How to declare "nextval('testing_thing_thing_id_seq'::regclass)" as default value for column "thing_id" in postgres table "testing_thing"?

在我的 postgres 数据库中有一个名为 testing_thing 的 table,我可以看到(通过 运行 \d testing_thing 在我的 psql 提示符下)它被定义为

                                        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 列的部分。

这是我用来创建 table:

的查询
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