【问题标题】:SQL Compact Double Foreign Key ProblemSQL Compact 双外键问题
【发布时间】:2011-01-24 21:38:42
【问题描述】:

以下是数据库的基本版本:

问题
uid - 主键 - int
qid - 主键 - 身份 - bigint
img - nchar
后日期 - 日期时间
标题 - nchar

用户个人资料
电子邮件 - nchar
UserId - 主键 - 身份 - int

投票
qid - 主键 - bigint
uid - 主键 - int
投票日期 - 日期时间
投票 - 位

我遇到的问题是我希望 Votes 的 uid 是 UserTable 的外键,而 Votes 的 qid 是 Questions 的外键(显然是 qid)。当我尝试添加与 WebMatrix 的关系时,我不断收到错误“引用的表必须具有主键或候选键”。我究竟做错了什么?

【问题讨论】:

  • 嗯,很多事情。为什么不发布带有表名和列名的真实示例——而不是通用的table-item——以便我们(我)可以提供帮助。
  • 指示哪个部分是 FK,哪个部分是它试图链接到的 PK
  • 将名称更改为原始名称。希望它会有所帮助
  • 双外键...一路...

标签: sql sql-server-ce webmatrix


【解决方案1】:

外键必须引用另一个表中的唯一键。从您的问题来看,您是否打算让 item1 或 item2 成为 PK,或者 (item1, item2) 的组合是否是唯一的,这一点尚不清楚。如果是组合,那么这是另一个表中外键的唯一有效链接。

问题的 PK 由两列组成,因此要创建从投票到问题的 FK,您需要 2 列来加入它。然而,最好只用一列创建一个简单的 PK。然后,你的 FK 就可以工作了。

投票 qid - 主键 - bigint uid - 主键 - int 投票日期 - 日期时间 投票位 问题 qid - 主键 - 身份 - bigint uid - 整数 img - nchar 后日期 - 日期时间 标题 - nchar

您可以在 Question (uid, qid) 上创建索引,但不要将其作为 PK。

【讨论】:

    【解决方案2】:

    不熟悉WebMatrix,所以我不知道它是否特别有复合键的问题。

    但是,我确实注意到,问题中的主键是 (uid, qid),这与将投票中的 qid(本身)作为问题的外键不兼容。

    【讨论】:

      【解决方案3】:

      create table UserProfile (
            UserID  integer identity primary key
          , Email   nvarchar(512)
      );
      
      create table Question (
            QuestionID integer identity primary key
          , OwnerID    integer 
          , PostDate   datetime
          , Title      nvarchar(1000)
      );
      alter table Question
          add constraint fk1_Question foreign key (OwnerID) references UserProfile (UserID); 
      
      
      create table Vote (
            UserID      integer
          , QuestionID  integer
          , VoteDate    datetime
      );
      alter table Vote
          add constraint pk1_Vote primary key (UserID, QuestionID)
        , add constraint fk1_Vote foreign key (UserID)      references UserProfile (UserID);
        , add constraint fk2_Vote foreign key (QuestionID)  references Question (QuestionID);
      

      【讨论】:

        【解决方案4】:

        我遇到了同样的问题,无意中找到了解决方案。

        您需要确保主键索引表与关系中的字段顺序相同。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-16
          • 1970-01-01
          相关资源
          最近更新 更多