0

我有以下表格:PostgreSQL的外鍵和子表

--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居然給我的存儲multiquestion行。

編輯:

簡化到:

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

給了我同樣的錯誤;

+0

你在哪裏插入'Tr.Questions'? – FuzzyTree

+0

我插入從'Tr.Questions'繼承的'Tr.MultiQuestions'。還有其他問題類型(未顯示),例如'Tr.TrueFalse'' Tr.ShortAnswer',它也繼承自'Tr.Questions' – moesef

+0

我的意圖是允許使用任何類型的問題作爲FK在CompetitionsQuestions表中 – moesef

回答

1

(假定,從評論,您使用PostgreSQL的表繼承功能,因爲你的問題並沒有真正包含關於模式的全面信息,以及如何填充內容):

外鍵不適用於繼承樹的所有成員。他們只能到特定的表。

約束UNIQUEPRIMARY KEY也是如此。

你可以看到一個外鍵約束將在一個表中看到,如果你:

SELECT * FROM ONLY thetable; 

ONLY關鍵字告訴PostgreSQL的不包含子表。這就是外鍵約束檢查中使用的。