26

我在 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.

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

4

3 回答 3

27

您可以执行以下操作,但最好将其包含在创建表中,如 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;
于 2016-09-07T21:37:46.680 回答
18

为什么不在 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)
)
于 2012-03-28T11:44:47.943 回答
10

您可以在创建它之前尝试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中。

于 2019-05-20T14:32:23.227 回答