繁体   English   中英

PostgreSQL外键和子表

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM