【问题标题】:PostgreSQL Error: Relation already exists - FOREIGN KEY in CREATE TABLEPostgreSQL 错误:关系已存在 - CREATE TABLE 中的 FOREIGN KEY
【发布时间】:2019-02-05 15:53:26
【问题描述】:

我正在制作如下表格:

CREATE TABLE creator.lists
(
    _id bigserial PRIMARY KEY NOT NULL,
    account_id bigint NOT NULL,
    created timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
    display_name text DEFAULT '',
    name text DEFAULT '',
    extra jsonb,

    FOREIGN KEY (account_id)
        REFERENCES creator.accounts (_id)
            ON DELETE CASCADE
);

但我收到此错误:

ERROR:  relation "account_id_index" already exists

当我跑步时:

CREATE INDEX
    account_id_index
ON
    creator.lists
(
    account_id
);

如何在外键上创建索引?我正在运行 v11.1

请注意,我之前也为另一个表运行过类似的命令:

CREATE INDEX
    account_id_index
ON
    creator.contacts
    (
        account_id
    );

我不认为索引名称在表之间需要是唯一的?

【问题讨论】:

    标签: database postgresql indexing namespaces


    【解决方案1】:

    索引与表、视图和序列位于相同的命名空间中,因此您不能在一个架构中对任何这些对象使用相同的名称两次。

    要么选择一个不同的名称,要么让 PostgreSQL 为您选择一个:

    CREATE INDEX ON creator.lists (account_id);
    

    【讨论】:

    • 我决定让 psql 为我做这件事 :)
    【解决方案2】:

    好的,似乎索引名称需要是唯一的,因为删除命名修复它:

    CREATE INDEX
    ON
        creator.contacts
        (
            account_id
        );
    

    来自docs

    name
    The name of the index to be created. No schema name can be included here; the index is always created in the same schema as its parent table. If the name is omitted, PostgreSQL chooses a suitable name based on the parent table's name and the indexed column name(s).
    

    【讨论】:

      猜你喜欢
      • 2014-11-10
      • 1970-01-01
      • 2020-08-11
      • 2016-07-06
      • 2021-08-31
      • 2021-04-24
      • 1970-01-01
      • 2017-05-19
      • 1970-01-01
      相关资源
      最近更新 更多