如何在PostgreSQL上启动一个id为最大值且自动递增-1的表?
我需要创建一个在max int上具有初始值的表,并且必须是自动增量,但自动增量必须是-1。
我知道如何创建表格:
CREATE TABLE "external_sequence" ("id" int NOT NULL, "created_at" timestamp NOT NULL DEFAULT now(), "updated_at" timestamp NOT NULL DEFAULT now(), CONSTRAINT "PK_119c50ca5604d166b77b8585a2c" PRIMARY KEY ("id"))但在这种情况下,表从id 1开始,每行递增,我必须在不设置我不知道的数字的情况下开始,mey是postgres函数,从最大值开始,每行递增-1。
这个是可能的吗?
我正在尝试使用node.js和typeorm来实现这一点,但是如果需要的话,我可以使用查询。我希望你能听懂我糟糕的英语。
发布于 2020-11-05 01:55:15
CREATE SEQUENCE my_custom_sequence START WITH 2147483647 INCREMENT BY -1 MAXVALUE 2147483647 MINVALUE 1;
-- if you already have sequence want to modify:
-- alter sequence my_custom_sequence INCREMENT BY -1;
-- ALTER SEQUENCE my_custom_sequence RESTART WITH 2147483647;
CREATE TABLE tests (
id integer not null default nextval('my_custom_sequence'),
name VARCHAR ( 255 ) NOT NULL
);
insert into tests(name) values('first');
insert into tests(name) values('second');
insert into tests(name) values('third');
select * from tests;
id | name
------------+--------
2147483647 | first
2147483646 | second
2147483645 | third更多信息:https://www.postgresql.org/docs/current/sql-altersequence.html
https://stackoverflow.com/questions/64684853
复制相似问题