我正在创建表来处理数据库中的安全问题/选定问题/给定答案部分并收到此错误:
没有唯一约束匹配给定引用表的键#34; m_security_questions"
我不知道如何解决这个问题?
(由于架构不会构建错误的b / c,我无法添加SQL小提琴)
CREATE TABLE security_question --defines questions
(
id SERIAL PRIMARY KEY NOT NULL,
question character varying(1024) NOT NULL,
is_custom boolean DEFAULT FALSE NOT NULL
);
INSERT INTO security_question
(question,is_custom)
VALUES
('do you know the answer?',FALSE),
('Write your own question',TRUE);
CREATE TABLE m_security_questions
( --defines question a member chooses & allows free form question
-- id SERIAL NOT NULL,
-- I know adding id like this and making keeping same pk solves it
-- but isn't storing the extra sequence not needed?
member integer --REFERENCES member(m_no)
-- commented out reference for so only
NOT NULL,
question integer REFERENCES security_question(id) NOT NULL,
m_note text,
PRIMARY KEY(member,question)
);
-- here I add unique constraint but doesn't the primary already mean I have a unique index?
ALTER TABLE m_security_questions ADD CONSTRAINT m_security_questions_unique_member_question UNIQUE (member,question);
INSERT INTO m_security_questions
(member,question,m_note)
VALUES
(2,1,NULL),
(2,2,'How many marbles in this jar?');
CREATE TABLE m_security_answer --defines members given answer
( -- I want member & question here to line up w/ same from m_security_questions
member integer REFERENCES m_security_questions(member),
question integer REFERENCES m_security_questions(question) NOT NULL,
answer character varying(255) NOT NULL,
PRIMARY KEY (member,question)
);
-- here is where I get the error:
-- there is no unique constraint matching given keys for referenced table "m_security_questions"
INSERT INTO m_security_answer
(member,question,answer)
VALUES
(2,1,'yes'),
(2,2,'431');
答案 0 :(得分:2)
主键肯定定义了一个唯一约束。但唯一的约束是(成员,问题)。你有两个FOREIGN KEY约束,分别引用(member)和(question)。
我很确定你想要的是:
CREATE TABLE m_security_answer --defines members given answer
(
member integer,
question integer NOT NULL,
answer character varying(255) NOT NULL,
PRIMARY KEY (member,question),
FOREIGN KEY (member, question) REFERENCES m_security_questions(member, question)
);