1

示例架构:http ://sqlfiddle.com/#!1/3d410

我已经有一个表,我想在表中添加一个新的、无效的外键。添加 NOT VALID 外键的正确语法是什么?

CREATE TABLE junks (
  id serial PRIMARY KEY,
  name text
);

CREATE TABLE trunks (
  id serial PRIMARY KEY,
  name text
  -- no fk
);

-- and the below does not work!

--ALTER TABLE trunks ADD junk serial REFERENCES junks(id) NOT VALID;
4

2 回答 2

4

您首先添加列:

alter table trunks add column junk serial;

然后将约束添加到表中:

alter table trunks add constraint the_constraint_name
    FOREIGN KEY (junk)
    REFERENCES junks (id)
    not valid;
于 2012-12-20T13:06:28.487 回答
1

这有效:

ALTER TABLE trunks ADD CONSTRAINT FK_junk_id 
  FOREIGN KEY (id) 
  REFERENCES junks(id) 
  NOT VALID
;

参见,例如:http ://www.postgresql.org/docs/devel/static/ddl-alter.html#AEN2758

于 2012-12-20T13:12:07.743 回答