[英]PostgreSQL Foreign Key and Child Tables
我有以下表格:
--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);
給我同樣的錯誤;
(從注釋中假定您正在使用PostgreSQL的表繼承功能,因為您的問題實際上並未包含有關模式以及如何填充其內容的完整信息):
外鍵不適用於繼承樹的所有成員。 它們只能到特定的表。
UNIQUE
約束或PRIMARY KEY
也是如此。
如果您執行以下操作,則可以看到表中將看到的外鍵約束:
SELECT * FROM ONLY thetable;
ONLY
關鍵字告訴PostgreSQL不包括子表。 這就是外鍵約束檢查中所使用的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.