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

时间:2013-10-01 16:09:06

标签: mysql database database-design foreign-keys

我正在尝试创建一些代表梦幻足球联赛的桌子,这些桌子本身包含球队,球队本身包含被选中的球员,他们是有统计数据的球员。我现在有一个非常基本的草案,我正在尝试让我的外键工作,但是,当我尝试添加密钥时,我不断收到此错误:

ERROR 1005 (HY000) at line 19: Can't create table 'football_db.PickedPlayers' (errno: 150)

我当然用Google搜索了一下,问题出现了,正如该错误信息所示,该问题与该表上的外键有关。

我可以不添加多组外键吗?还是我选择的外键类型?提前谢谢。

CREATE TABLE football_db.Leagues
    (league_id INT NOT NULL,
     league_name VARCHAR(100),
     PRIMARY KEY (league_id))
    ENGINE=INNODB;
CREATE TABLE football_db.Teams
    (league_id INT NOT NULL,
     team_id INT NOT NULL,
     team_name VARCHAR(100),
     PRIMARY KEY (league_id,team_id),
     FOREIGN KEY (league_id) REFERENCES Leagues(league_id))
    ENGINE=INNODB;
CREATE TABLE football_db.PickedPlayers
    (league_id INT NOT NULL,
     team_id INT NOT NULL,
     player_id INT NOT NULL,
     PRIMARY KEY (player_id),
     FOREIGN KEY (league_id,team_id) REFERENCES Teams(league_id,team_id),
     FOREIGN KEY (player_id) REFERENCES Players(player_id))
    ENGINE=INNODB;
CREATE TABLE football_db.Players
    (player_id INT NOT NULL,
     player_name VARCHAR(50),
     position VARCHAR(10),
     is_free_agent BOOL,
     PRIMARY KEY (player_id))
    ENGINE=INNODB;

2 个答案:

答案 0 :(得分:1)

在创建此表之前,您正在引用表players,只需在最后位置移动创建表CREATE TABLE football_db.PickedPlayers

 CREATE TABLE Leagues
(league_id INT NOT NULL,
 league_name VARCHAR(100),
 PRIMARY KEY (league_id))
ENGINE=INNODB;
CREATE TABLE Teams
(league_id INT NOT NULL,
 team_id INT NOT NULL,
 team_name VARCHAR(100),
 PRIMARY KEY (league_id,team_id),
 FOREIGN KEY (league_id) REFERENCES Leagues(league_id))
ENGINE=INNODB;
CREATE TABLE Players
(player_id INT NOT NULL,
 player_name VARCHAR(50),
 position VARCHAR(10),
 is_free_agent BOOL,
 PRIMARY KEY (player_id))
ENGINE=INNODB;
CREATE TABLE PickedPlayers
(league_id INT NOT NULL,
 team_id INT NOT NULL,
 player_id INT NOT NULL,
 PRIMARY KEY (player_id),
 FOREIGN KEY (league_id,team_id) REFERENCES Teams(league_id,team_id),
 FOREIGN KEY (player_id) REFERENCES Players(player_id))
ENGINE=INNODB;

Live working demo

答案 1 :(得分:0)

因此,当我打字时,我自己想出了问题。想想我至少会在这里发布我的解决方案,因为其他人可能会遇到同样的问题(非常愚蠢和愚蠢)。

问题是我在PickedPlayers之前创建了Players表,所以它不知道它应该引用Players的哪个外键,因为它不存在爱好。