在Postgres中添加NOT VALID外键

时间:2012-12-20 12:46:59

标签: postgresql foreign-keys ddl

示例架构: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;

2 个答案:

答案 0 :(得分:4)

首先添加列:

alter table trunks add column junk serial;

然后将约束添加到表中:

alter table trunks add constraint the_constraint_name
    FOREIGN KEY (junk)
    REFERENCES junks (id)
    not valid;

答案 1 :(得分: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