Postgres 截断重新启动身份不会重新启动身份

bbl*_*ack 5 postgresql

和题目说的差不多。

truncate table "Account" restart identity cascade;
insert into "Account" ("name", "enabled") values ("test", 1);
select * from "Account";
Run Code Online (Sandbox Code Playgroud)

输出:

 accountId | name | enabled
-----------+------+---------
        14 | test |       1
(1 row)
Run Code Online (Sandbox Code Playgroud)

这是表的架构:

                                       Table "public.Account"
  Column   |          Type          |                           Modifiers
-----------+------------------------+---------------------------------------------------------------
 accountId | integer                | not null default nextval('"Account_accountId_seq"'::regclass)
 name      | character varying(255) | not null
 enabled   | integer                | not null
Indexes:
    "Account_pkey" PRIMARY KEY, btree ("accountId")
Referenced by:
    TABLE ""AccountPropertyAccess"" CONSTRAINT "AccountPropertyAccess_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("accountId")
    TABLE ""User"" CONSTRAINT "User_accountId_fkey" FOREIGN KEY ("accountId") REFERENCES "Account"("accountId")
Run Code Online (Sandbox Code Playgroud)

这里有一些额外的词,因为堆栈交换认为我没有足够的词,因为我有太多的代码。

a_h*_*ame 5

似乎您没有将列创建为 serial列,因此 Postgres 不知道该序列“属于”该列,因此“重新启动身份”不会重置该序列。

您可以通过使用serial代替integer和默认值重新创建表来解决该问题。

或者你可以告诉 Postgres 该列“拥有”序列:

alter sequence "Account_accountId_seq" owned by "Account"."accountId";
Run Code Online (Sandbox Code Playgroud)

顺便说一句:使用带引号的标识符通常比它的价值要麻烦得多(至少以我的经验)。大多数情况下,最好不要使用带引号的标识符,例如create table Account (...)代替create table "Account" (...)