PostgreSQL外键和子表

时间:2014-07-19 06:16:26

标签: sql foreign-keys single-table-inheritance postgresql-9.3

我有以下表格:

--Competition tables
CREATE TABLE IF NOT EXISTS Tr.Competitions(
    competition_id      SERIAL PRIMARY KEY,
    competition_name    text NOT NULL
);

CREATE TABLE IF NOT EXISTS Tr.CompetitionsQuestions(
    competition_id      int NOT NULL,
    question_id         int NOT NULL,
    FOREIGN KEY (competition_id) REFERENCES Tr.Competitions(competition_id),
    FOREIGN KEY (question_id) REFERENCES Tr.Questions(question_id)
);

--Questions tables
CREATE TABLE IF NOT EXISTS Tr.Questions(
    question_id         SERIAL PRIMARY KEY,
    question_text       text NOT NULL
);

CREATE TABLE IF NOT EXISTS Tr.MultiQuestions(
    possible_answers    text ARRAY NOT NULL,
    correct_answer      int NOT NULL
) INHERITS(Tr.Questions);

我尝试将一些虚拟数据插入到Tr.CompetitionQuestions中,如下所示:

--Test Fixtures
INSERT INTO Tr.MultiQuestions (question_text, possible_answers, correct_answer) 
    VALUES ('Which of the following is awesome?', '{"Indian Food","Soccer","All the above"}', 2);

INSERT INTO Tr.Competitions(competition_name)
    VALUES ('Awesome Competition');

INSERT INTO Tr.CompetitionsQuestions(competition_id, question_id) 
    VALUES ((SELECT competition_id FROM Tr.Competitions WHERE competition_id=1),
            (SELECT question_id FROM Tr.Questions WHERE question_id=1));

将这些存储在.sql文件中并运行\i some.sql会导致以下错误。如何在CompetitionsQuestions表中添加问题外键?

 ERROR:  insert or update on table "competitionsquestions" violates foreign key constraint "competitionsquestions_question_id_fkey"      
DETAIL:  Key (question_id)=(1) is not present in table "questions". 

似乎是一个奇怪的错误,因为SELECT * FROM tr.questions WHERE question_id=1实际上给了我存储的多字符行。

编辑:

简化为:

INSERT INTO Tr.CompetitionsQuestions(competition_id, question_id) 
    VALUES (1, 1);

给了我同样的错误;

1 个答案:

答案 0 :(得分:1)

(假设您在评论中表示您正在使用PostgreSQL的表继承功能,因为您的问题并不真正包含有关架构的完整信息以及如何填充其内容):

外键不适用于继承树的所有成员。它们只能是特定的表。

UNIQUE约束或PRIMARY KEY

也是如此

如果你:

,你可以看到外键约束在表格中会看到什么
 SELECT * FROM ONLY thetable;

ONLY关键字告诉PostgreSQL不要包含子表。这是外键约束检查中使用的内容。