Postgres的truncate restart identity命令无法重新启动identity。

5
基本上就像主题所说的那样。
truncate table "Account" restart identity cascade;
insert into "Account" ("name", "enabled") values ("test", 1);
select * from "Account";

输出:

 accountId | name | enabled
-----------+------+---------
        14 | test |       1
(1 row)

这是该表的模式:
                                       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")

这是一些额外的文字,因为Stack Exchange认为我没有足够的文字,因为我有太多的代码。

1
显示表模式 \d "Account" - Clodoaldo Neto
你在第一个代码块中的插入语句是无效的。字符串字面值必须使用单引号,“test”表示列而不是值。 - user330315
3个回答

9

看起来您没有将列创建为 serial 列,因此Postgres不知道序列“属于”哪个列,因此“重新启动标识”不会重置序列。

您可以通过使用 serial 而不是 integer 和默认值重新创建表来修复它。

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

alter sequence "Account_accountId_seq" owned by "Account"."accountId";

顺带一提:在我的经验中,使用带引号的标识符通常会带来更多的麻烦,而收益甚微。大多数情况下,最好根本不使用带引号的标识符,例如使用create table Account (...)代替create table "Account" (...)


3

看起来你有一个自增序列ID。你还需要重置它。

《PostgreSQL文档》显示

ALTER SEQUENCE Account RESTART WITH 1;

关于此问题,这里这里有一些相关的问题。


2
我发现了更简单的方法。
TRUNCATE TABLE Account RESTART IDENTITY;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接