2011-01-24 27 views
1

下面是數據庫的基本版本:

問題
UID - 主鍵 - 詮釋
QID - 主鍵 - 認同 - BIGINT
IMG - NCHAR
踵 - 日期時間
標題 - NCHAR
SQL緊湊型雙外語關鍵問題

用戶配置
電子郵件 - NCHAR
用戶ID - PRIMAR Y鍵 - idendity - 詮釋

投票
QID - 主鍵 - BIGINT
UID - 主鍵 - 詮釋
votedate - 日期時間
投票 - 位

我遇到的問題是我希望uotes的Votes是來自UserTable的外鍵,而Votes的qid是來自Questions(顯然是qid)的外鍵。當我嘗試添加與WebMatrix的關係時,我總是收到錯誤「被引用的表必須具有主鍵或候選鍵。」我究竟做錯了什麼?

+0

好吧,很多事情。你爲什麼不發佈真正的例子,使用表名和列名 - 而不是通用的`table-item` - 以便我們(I)可以提供幫助。 – 2011-01-24 21:42:41

+0

指示哪個部分是FK,哪個部分是它試圖鏈接到 – RichardTheKiwi 2011-01-24 21:45:34

回答

1

外鍵必須引用另一個表中的一個獨特的密鑰。從你的問題,你是否打算將item1或item2作爲PK還是(item1,item2)的組合是唯一的並不清楚。如果是組合,那麼這是來自另一個表的外鍵的唯一有效鏈接。

問題的PK是由兩列,所以從投票創建FK到的問題,你需要2列加入到它。然而,只用一列創建一個簡單的PK會更好。然後,你的FK將起作用。

 
Votes 
qid - primary key - bigint 
uid - primary key - int 
votedate - datetime 
vote - bit 

Questions 
qid - primary key - identity - bigint 
uid - int 
img - nchar 
postdate - datetime 
title - nchar 

您可以在問題(uid,qid)上創建一個索引,但不要使該PK成爲可能。

0

不熟悉WebMatrix的,所以我不知道,如果它,特別是有問題的複合鍵。

我的確注意到,然而,在問題的主鍵(UID,QID),這是不兼容的票數(本身)已經QID是一個外鍵的問題。

0

enter image description here

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

我有同樣的問題的時候,突然發現了一個解決方案。

您需要確保主鍵索引表有字段的順序相同的關係。