我不能一个外键约束添加到我创造它的错误了这样一个数据库,也请让我知道,如果有问题,我的逻辑设计,我想创建一个REST API利用这个数据库结构。我想练我的数据库设计技巧,所以这是一个玩具的例子。
当前数据库架构
use ToolsDB;
create table player(
player_id INT NOT NULL AUTO_INCREMENT,
firstname VARCHAR(100) NOT NULL,
lastname VARCHAR(40) NOT NULL,
nickname VARCHAR(40) NOT NULL,
wins integer,
losses integer,
current_win_streak integer,
created DATETIME,
last_seen DATETIME,
PRIMARY KEY ( player_id )
);
create table Attacker_Battles(
attacker_id INT NOT NULL AUTO_INCREMENT,
battle_id INT NOT NULL,
player_id INT NOT NULL,
PRIMARY KEY ( attacker_id ),
FOREIGN KEY (battle_id) REFERENCES Battles (battle_id),
FOREIGN KEY (attacker_id) REFERENCES player (attacker_id)
);
create table Defender_Battles(
defender_id INT NOT NULL AUTO_INCREMENT,
battle_id INT NOT NULL,
player_id INT NOT NULL,
PRIMARY KEY ( defender_id ),
FOREIGN KEY (battle_id) REFERENCES Battles (battle_id),
FOREIGN KEY (defender_id) REFERENCES player (defender_id)
);
create table Winner_Battles(
winner_id INT NOT NULL AUTO_INCREMENT,
battle_id INT NOT NULL,
player_id INT NOT NULL,
PRIMARY KEY ( winner_id ),
FOREIGN KEY (battle_id) REFERENCES Battles (battle_id),
FOREIGN KEY (winner_id) REFERENCES player (player_id)
);
create table Battles(
battle_id INT NOT NULL AUTO_INCREMENT,
starttime DATETIME,
endtime DATETIME,
PRIMARY KEY ( battle_id )
);
10:32:30 create table Attacker_Battles( attacker_id INT NOT NULL AUTO_INCREMENT, battle_id INT NOT NULL, player_id INT NOT NULL, PRIMARY KEY ( attacker_id ), FOREIGN KEY (battle_id) REFERENCES Battles (battle_id), FOREIGN KEY (attacker_id) REFERENCES player (attacker_id) ) Error Code: 1215. Cannot add foreign key constraint 0.020 sec
你不需要attacker_id
作为attacker_battles
表的外键,因为它是主键。我想你想的player_id
链接到player
表。所以使用player_id
外键。