gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 13:33:16 28 4
gpt4 key购买 nike

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

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;

最佳答案

在创建此表之前,您要引用表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

关于mysql - 尝试使用外键创建表时出现错误 1005,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19120982/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com