1

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

问题
uid - 主键 - int
qid - 主键 - 身份 - bigint
img - nchar
postdate - datetime
title - nchar

UserProfile
电子邮件 - nchar
UserId - 主键 - 身份 - int

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

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

4

4 回答 4

1

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

Questions 的 PK 由两列组成,因此要创建从 Vote 到 Question 的 FK,您需要 2 列加入它。然而,最好只用一列创建一个简单的 PK。然后,您的 FK 将起作用。

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

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

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

于 2011-01-24T21:43:40.327 回答
0

在此处输入图像描述

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);
于 2011-01-24T22:21:46.083 回答
0

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

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

于 2012-06-02T17:55:27.627 回答
0

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

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

于 2011-01-24T22:01:19.607 回答