0

我正在尝试创建一些代表梦幻足球联赛的表格,它本身包含球队,它本身包含挑选的球员,他们是有统计数据的球员。我现在有一个非常基本的草稿,并且正在尝试使外键正常工作,但是,当我尝试添加键时,我不断收到此错误:

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

我当然已经用谷歌搜索了一下,正如该错误消息所表明的那样,问题与我在该表上的外键有关。

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

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;
4

2 回答 2

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;

现场工作演示

于 2013-10-01T16:17:30.380 回答
0

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

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

于 2013-10-01T16:09:06.007 回答