2017-03-07 50 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));