【问题标题】:Add primary key to PostgreSQL table only if it does not exist仅当 PostgreSQL 表不存在时才添加主键
【发布时间】:2012-04-11 23:52:33
【问题描述】:

我在 Postgres 9.1 中有简单的表格创建脚本。我需要它来创建表 2-属性 PK 仅当它不存在时。

CREATE TABLE IF NOT EXISTS "mail_app_recipients"
(
    "id_draft" Integer NOT NULL,
    "id_person" Integer NOT NULL
) WITH (OIDS=FALSE); -- this is OK

ALTER TABLE "mail_app_recipients" ADD PRIMARY KEY IF NOT EXISTS ("id_draft","id_person");
-- this is problem since "IF NOT EXISTS" is not allowed.

任何解决方案如何解决这个问题?提前致谢。

【问题讨论】:

    标签: sql postgresql primary-key alter-table postgresql-9.1


    【解决方案1】:

    您可以执行以下操作,但最好按照 a_horse_with_no_name 的建议将其包含在创建表中。

    if NOT exists (select constraint_name from information_schema.table_constraints where table_name = 'table_name' and constraint_type = 'PRIMARY KEY') then
    
    ALTER TABLE table_name
      ADD PRIMARY KEY (id);
    
    end if;
    

    【讨论】:

    • 注意这段代码应该在DO $$ BEGIN ... END $$;,see内执行
    【解决方案2】:

    为什么不在 CREATE TABLE 中包含 PK 定义:

    CREATE TABLE IF NOT EXISTS mail_app_recipients
    (
        id_draft Integer NOT NULL,
        id_person Integer NOT NULL,
        constraint pk_mail_app_recipients primary key (id_draft, id_person)
    )
    

    【讨论】:

    • 谢谢,这就是我想要的。如果不存在单独添加主键是不可能的?
    • 不,ALTER TABLE 语句没有 IF NOT EXISTS 选项。
    • 很酷的东西,用 Ansible 帮助我优雅地实现幂等性!
    【解决方案3】:

    你可以在创建它之前尝试DROP它(DROPIF EXISTS子句):

    ALTER TABLE mail_app_recipients DROP CONSTRAINT IF EXISTS mail_app_recipients_pkey;
    ALTER TABLE mail_app_recipients ADD CONSTRAINT mail_app_recipients_pkey PRIMARY KEY ("id_draft","id_person");
    

    请注意,这需要您为主键约束命名 - 在本例中为 mail_app_recipients_pkey

    【讨论】:

      猜你喜欢
      • 2016-10-19
      • 1970-01-01
      • 2023-03-19
      • 2021-04-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2021-12-03
      • 1970-01-01
      相关资源
      最近更新 更多