【資料庫】postgresql資料庫建立自增序列id的注意事項
阿新 • • 發佈:2019-07-26
1.建立一張表
CREATE TABLE "public"."tt" (
"name" varchar(128),
"status" int4 DEFAULT 2,
"id" int8 NOT NULL,
CONSTRAINT "tt_pkey" PRIMARY KEY ("id")
)
WITH (OIDS=FALSE)
;
ALTER TABLE "public"."tt" OWNER TO "postgres";
2.建立與表對應的自增序列
CREATE SEQUENCE tt_id_seq
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER TABLE public.tt_id_seq OWNER TO postgres;
#最重要的,不執行下面這句的話,匯出的sql.json中id的sequence值會為null
ALTER SEQUENCE tt_id_seq OWNED BY tt.id;
ALTER table tt ALTER column id set default nextval('tt_id_seq');
SELECT pg_catalog.setval('tt_id_seq', 1, false);
發現sequence不存在的情況
解決思路:刪除相關表和依賴進行重建
---補充(繞了一大圈,從《PostgreSQL修煉之道》可以發現)
序列型別
CREATETABLE t (id SERIAL);
等價於
CREATE SEQUENCE t_id_seq;
CREATE TABLE t ( id integer NOT NULL DEFAULT nextval(‘t_id_seq’) );
ALTER SEQUENCE t_id_seq OWNED BY t_id;
--------------------- &n