2017-03-07 77 views
0

如果有人可以幫我這個劇本我將不勝感激。SQL外鍵

所以我基本上是試圖用一個外鍵引用表多個主鍵,我不斷收到一個錯誤。當我運行私人教練的創建表腳本時,出現此錯誤:

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

這是兩個表的CREATE TABLE腳本。我正試圖在私人教練中使用外鍵來按計劃參考表格。 FitnessWebApp是數據庫的名稱。

use FitnessWebApp 

create table Schedule 
(
    day char(20), 
    time char(20), 
    name char(30), 
    gymName char(30) 
    primary key (name, gymName, day, time) 
); 

use FitnessWebApp 

create table Personal_Trainer 
(
    name char(30), 
    gymName char(30) 
    primary key(name, gymName), 
    foreign key (name, gymName) REFERENCES Schedule(name, gymName) 
); 
+0

http://stackoverflow.com/search?q=%5Bsql-server%5D+There+are+no+primary+or+candidate+keys+in +在+引用+表 –

+0

有沒有這樣的東西「有多個主鍵的表」 - 你有一個表有* *複合主鍵。只能有一個主鍵。它看起來對我像你想圍繞創建FK錯誤的方式(不應該的時間表引用的教練,而不是相反?) –

回答

0

試試這個:

create table Personal_Trainer (
    id int(10) not null, 
    trainerName char(30), 
    primary key (id)); 

create table gym (
    id int(10) not null, 
    gymName char(30), 
    primary key (id)); 

create table Schedule (
    id int (10) not null, 
    trainerId int(10), 
    gymId int(10), 
    gymDay Date, 
    gymTime Datetime, 
    primary key (id), 
    foreign key (trainerId) REFERENCES Personal_Trainer (id), 
    foreign key (gymId) REFERENCES gym (id));