2013-03-12 80 views
-1

我在我的數據庫中創建表,並且在嘗試創建表之間的關係時出現奇怪的問題。試圖建立關係時發生SQL查詢問題

這裏是我的查詢:

CREATE TABLE ogrnizationarticle (
    OAID Int NOT NULL , 
    _Text VARCHAR(255) NOT NULL , 
    ARank Int NULL DEFAULT NULL , 
    Acomment VARCHAR(255) NULL DEFAULT NULL , 
    Author VARCHAR(45) NULL DEFAULT NULL , 
    PRIMARY KEY (OAID, _Text) , 
    foreign key (OAID) references organization(OID), 
); 
-- ----------------------------------------------------- 
-- Table nasshope.organization_Article_comment 
-- ----------------------------------------------------- 
CREATE TABLE organizationArticleComment (
    O_Article_ID Int NOT NULL , 
    Comment VARCHAR(255) NOT NULL , 
    Article VARCHAR(255) NOT NULL , 
    Comment_Like Int NULL DEFAULT NULL , 
    _Date DATETIME NULL DEFAULT NULL , 
    PRIMARY KEY (O_Article_ID, Comment, Article) , 
    foreign key (O_Article_ID) references ogrnizationarticle(OAID), 
); 

這裏是錯誤

Msg 1776, Level 16, State 0, Line 13 
There are no primary or candidate keys in the referenced table 'ogrnizationarticle' that match the referencing column list in the foreign key 'FK__organizat__O_Art__42ACE4D4'. 
Msg 1750, Level 16, State 0, Line 13 
Could not create constraint. See previous errors. 
+0

它拼寫正確嗎? – Randy 2013-03-12 22:40:24

+0

您需要在'ogrnizationarticle'中有一個與foerign鍵匹配的鍵,但是'ogrnizationarticle'中的主鍵有兩列。 – madth3 2013-03-12 22:46:32

回答

1

對於這個工作,你就需要將_Text列添加到organizationArticleComment,並使用

foreign key (O_Article_ID,_Text) references organization(OAID,_Text)

但是我不建議你這樣做

OAID,_Text在我看來並不爲ogrnizationarticle一個很好的主鍵。我會在那裏使用代理PK(IDENTITY),然後您只需將其包含在organizationArticleComment中。

否則,您最終需要跨表複製一個可能相當寬且不穩定的密鑰。由於PK也是該表上的聚簇索引,因此應該意識到聚簇索引鍵也包含在表中的任何非聚簇索引中。

+2

@axrwkr - 是的,好點。 OP應該只是選擇一個名字並堅持下去。而不是'O_Article_ID'與'OID'與'OAID'。在修復「ogrnization」錯誤的同時修復! – 2013-03-12 22:39:14

0

OAIDogrnizationarticle中的字段必須是唯一密鑰或主鍵。

請參閱Candidate key瞭解更多信息。