【问题标题】:postgresql unique constraint not unique enoughpostgresql 唯一约束不够唯一
【发布时间】:2013-08-16 17:04:54
【问题描述】:

我正在创建表格来处理我们数据库的安全问题/选定问题/给定答案部分并收到此错误:

引用表“m_security_questions”的给定键没有唯一约束匹配

不知道如何解决这个问题?

(由于架构不会构建错误的 b/c,我无法添加 SQL Fiddle)

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');

【问题讨论】:

    标签: postgresql constraints unique


    【解决方案1】:

    主键明确定义了唯一约束。但是唯一的约束是在(成员,问题)上。您有两个 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)
      );
    

    【讨论】:

    • 我认为你是对的。正确答案限时 4 分钟。哈哈。你会这样做还是只是在 m_security_questions 上添加一个新的 id(在编辑中提到)?哪个最好?
    • 两列外键没有错。您可能需要注意缺少 NOT NULL 约束的列。 NULL 与 FOREIGN KEYS 有时会让人感到惊讶。而且 AFAICT 在其中一个表中不是 NULL,在另一个表中允许为 NULL。
    • 我在发布此消息后不久就看到了。两者都不应为空。
    猜你喜欢
    • 2018-12-02
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-20
    相关资源
    最近更新 更多