【问题标题】:Postgres truncate restart identity doesn't restart identityPostgres 截断重新启动身份不会重新启动身份
【发布时间】:2014-08-16 11:32:06
【问题描述】:

和题目说的差不多。

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")

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

【问题讨论】:

  • 显示表架构\d "Account"
  • 您在第一个代码块中的插入语句无效。字符串文字必须使用单引号 "test" 表示列,而不是值。

标签: postgresql


【解决方案1】:

我找到了更简单的方法

TRUNCATE TABLE Account RESTART IDENTITY;

【讨论】:

    【解决方案2】:

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

    您可以通过使用serial 而不是integer 和默认值重新创建表来解决此问题。

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

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

    顺便说一句:使用带引号的标识符通常比它的价值要麻烦得多(至少根据我的经验)。大多数时候最好不要使用带引号的标识符,例如create table Account (...) 而不是 create table "Account" (...)

    【讨论】:

      【解决方案3】:

      看起来您有一个自动递增序列 ID。您也需要重置它。

      PostgreSQL 文档shows

      ALTER SEQUENCE Account RESTART WITH 1;
      

      herehere 对此有几个问题。

      【讨论】:

        猜你喜欢
        • 2015-10-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多