代码之家  ›  专栏  ›  技术社区  ›  A. L

PostgreSQL错误:关系已存在-创建表中存在外键

  •  0
  • A. L  · 技术社区  · 7 年前

    我正在做一张桌子如下:

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

    我不认为表之间的索引名必须是唯一的?

    2 回复  |  直到 7 年前
        1
  •  4
  •   Laurenz Albe    7 年前

    索引与表、视图和序列位于同一名称空间中,因此在一个模式中,不能对这些对象使用同一名称两次。

    请选择其他名称,或让PostgreSQL为您选择一个名称:

    CREATE INDEX ON creator.lists (account_id);
    
        2
  •  1
  •   A. L    7 年前

    好的,似乎在删除命名时索引名需要唯一:

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