2013-08-16 229 views
0

我創建表來處理安全問題/選擇的問題/給出回答我們的數據庫的部分,收到此錯誤:PostgreSQL的唯一約束不夠唯一

沒有唯一約束相匹配的參考表「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'); 

回答

2

主鍵絕對定義的唯一約束。但唯一的約束是(成員,問題)。您有兩個分別引用(成員)和(問題)的FOREIGN KEY約束。

我敢肯定,你想要的是:

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) 
); 
+0

我認爲你是正確的。 4分鐘的正確答案限制。大聲笑。你會這樣做,或者只是在m_security_questions(在編輯中提到)上添加一個新的ID?哪個最好? – gooddadmike

+1

兩列外鍵沒有錯。您可能需要注意缺少NOT NULL約束的列。空值vs FOREIGN KEYS有時會讓人感到驚訝。 AFAICT在其中一個表中不是NULL,而在另一個表中允許NULL。 –

+0

我在發佈之後不久就看到了。兩者都是非空的。 – gooddadmike