2015-12-05 60 views
0

我想創建一個具有相同FK約束的幾個列的表。我的語法有什麼問題?我收到MSG 102,不正確的語法錯誤圍繞「fk_fighterID」用FK創建SQL表

「戰士」是已經設置了「fighterID」作爲PrimaryKey的

CREATE TABLE FIGHTS 
(
FIGHTID INT PRIMARY KEY, 
CONSTRAINT fk_fighterID FOREIGN KEY REFERENCES FIGHTERS(fighterID), 
FIGHTER_ID_CHALLANGER int fk_fighterID, 
FIGHTER_ID_CHALLANGED int fk_fighterID, 
CONSTRAINT fk_weightclass FOREIGN KEY (classID) REFERENCES WEIGHT_CLASSES 
     (classID) 
WEIGHTCLASS NOT NULL fk_wightclass, 
IS_MAIN BIT NOT NULL, 
IS_CO_MAIN BIT NOT NULL, 
SCHEDULED ROUNDS TINYINT(1), 
CONSTRAINT fk_WINMETH FOREIGN KEY (WINID) REFERENCES WINNING_METHODS (WINID) 
WINNING METHOD NOT NULL fk_WINMETH 
) 
; 

回答

1

正確說法: CONSTRAINT fk_weightclass FOREIGN KEY (classID) REFERENCES WEIGHT_CLASSES (classID)

錯誤的語句: CONSTRAINT fk_fighterID FOREIGN KEY REFERENCES FIGHTERS(fighterID),

你忘了提及類似'(CLASSID)'

編輯: 我不確定你試圖達到什麼,但你的上面的查詢是錯誤的,請嘗試下面的查詢是否有意義。

CREATE TABLE FIGHTS ( FIGHTID INT PRIMARY KEY, FIGHTER_ID_CHALLANGER INT, FIGHTER_ID_CHALLANGED INT, IS_MAIN BIT NOT NULL, IS_CO_MAIN BIT NOT NULL, SCHEDULED_ROUNDS TINYINT(1), WEIGHTCLASS INT NOT NULL, CLASS_ID INT NOT NULL, WINNING_METHOD INT NOT NULL, CONSTRAINT fk_fighterID FOREIGN KEY (FIGHTER_ID_CHALLANGER) REFERENCES FIGHTERS (fighterID), CONSTRAINT fk_weightclass FOREIGN KEY (CLASS_ID) REFERENCES WEIGHT_CLASSES (classID), CONSTRAINT fk_WINMETH FOREIGN KEY (WINNING_METHOD) REFERENCES WINNING_METHODS (WINID) );

+0

我擁有了如上兩種方式,我把它糾正了「正確的說法」,但仍然得到這讓我更接近錯誤 –

+0

- 我的目標是創建FK約束fk_fighterID,這樣我可以在2列上使用它。上面的代碼似乎很接近,但告訴我「戰士」引用了一個無效的表。 –

+0

我的部分更多的錯誤 - 需要引用PK。還需要匹配數據類型。我能夠讓我的桌子成立!謝謝 –

0

Shouldn`t的約束是一個表表創建語句像這樣外:

CREATE TABLE Sales.TempSalesReason (TempID int NOT NULL, Name nvarchar(50), 
CONSTRAINT PK_TempSales PRIMARY KEY NONCLUSTERED (TempID), 
CONSTRAINT FK_TempSales_SalesReason FOREIGN KEY (TempID) 
    REFERENCES Sales.SalesReason (SalesReasonID) 
    ON DELETE CASCADE 
    ON UPDATE CASCADE 
);