错误引用的表中没有主键或候选键

时间:2014-05-22 15:26:09

标签: sql database visual-studio-2012

尝试使用外键创建表时出现此错误:

  

引用的表'TeamToPlayers'中没有主键或候选键与外键'FKey2'中的引用列列表匹配。

我不明白为什么,表TeamToPlayers中有一个主键。

以下是查询:

create table TeamToPlayers
(TeamName varchar(50) NOT NULL,
  PlayerName varchar(50) NOT NULL,
  primary key(TeamName,PlayerName),
  CONSTRAINT FKey FOREIGN KEY (TeamName) REFERENCES Teams(TeamName)
)

create table Players
(PlayerName varchar(50) NOT NULL,
primary key(PlayerName),
CONSTRAINT FKey2 FOREIGN KEY (PlayerName) REFERENCES TeamToPlayers(PlayerName)
);

1 个答案:

答案 0 :(得分:3)

TeamToPlayers主键由两个字段组成 - 您必须引用它们,否则它不是键。我认为您可能错误地将密钥放在一边 - 它应该在TeamToPlayers上并引用Players,如下所示:

create table TeamToPlayers
(   
    TeamName varchar(50) NOT NULL,
    PlayerName varchar(50) NOT NULL,
    primary key(TeamName,PlayerName),
    CONSTRAINT FKey FOREIGN KEY (TeamName) REFERENCES Teams(TeamName),
    CONSTRAINT FKey2 FOREIGN KEY (PlayerName) REFERENCES Players(PlayerName)
)

create table Players
(PlayerName varchar(50) NOT NULL,
primary key(PlayerName),
);