PostgreSQL外键引用继承了表

时间:2015-08-06 06:22:23

标签: sql postgresql inheritance

我试图通过继承来简化我的代码。这就是我现在所拥有的

DROP SCHEMA PUBLIC CASCADE;
CREATE SCHEMA PUBLIC;

CREATE TABLE student(
   id SERIAL PRIMARY KEY,
   age INT
);

CREATE TABLE engineer(
   id SERIAL PRIMARY KEY,
   studentId INT REFERENCES student (id),
   friend INT REFERENCES student (id)
);

CREATE TABLE artist(
   id SERIAL PRIMARY KEY,
   studentId INT REFERENCES student (id),
   friend INT REFERENCES student (id)
);

INSERT INTO student (age) VALUES (20); --Trying to remove this
INSERT INTO student (age) VALUES (21); --Trying to remove this
INSERT INTO engineer (studentId) VALUES (1);
INSERT INTO artist (studentId,friend) VALUES (2,1);

我不想输入这两行,因此,我使用的是以下行

DROP SCHEMA PUBLIC CASCADE;
CREATE SCHEMA PUBLIC;

CREATE TABLE student(
   studentId SERIAL PRIMARY KEY,
   age INT
);

CREATE TABLE engineer(
   id SERIAL PRIMARY KEY,
   friend INT REFERENCES student (studentId)
) INHERITS (student);

CREATE TABLE artist(
   id SERIAL PRIMARY KEY,
   friend INT REFERENCES student (studentId)
) INHERITS (student);

INSERT INTO engineer (id,age) VALUES (DEFAULT,20);
INSERT INTO artist (id,age,friend) VALUES (DEFAULT,20,1);

但是我收到以下错误。

psql:test.psql:45: ERROR:  insert or update on table "artist"     
violates foreign key constraint "artist_friend_fkey"
DETAIL:  Key (friend)=(1) is not present in table "student".

这是添加到Postgres问题的长列表中的另一个限制吗?

2 个答案:

答案 0 :(得分:2)

是。看看docs 底部警告部分:

  

继承功能的一个严重限制是索引   (包括唯一约束)和外键约束仅适用   单个表,而不是他们的继承子

答案 1 :(得分:0)

我想我找到了解决方法。我只是将引用移动到父类中,如此

DROP SCHEMA PUBLIC CASCADE;
CREATE SCHEMA PUBLIC;

CREATE TABLE student(
   studentId SERIAL PRIMARY KEY,
   age INT,
   friend INT REFERENCES student (studentId)
);

CREATE TABLE engineer(
   id SERIAL PRIMARY KEY
) INHERITS (student);

CREATE TABLE artist(
   id SERIAL PRIMARY KEY
) INHERITS (student);

INSERT INTO engineer (id,age) VALUES (DEFAULT,20);
INSERT INTO artist (id,age,friend) VALUES (DEFAULT,20,1);