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);
給了我同樣的錯誤;
你在哪裏插入'Tr.Questions'? – FuzzyTree
我插入從'Tr.Questions'繼承的'Tr.MultiQuestions'。還有其他問題類型(未顯示),例如'Tr.TrueFalse'' Tr.ShortAnswer',它也繼承自'Tr.Questions' – moesef
我的意圖是允許使用任何類型的問題作爲FK在CompetitionsQuestions表中 – moesef