无法添加外键约束

时间:2019-02-03 15:44:08

标签: mysql

我无法向数据库添加外键约束,我正在创建此类错误,也请让我知道我的逻辑设计是否存在问题,我正在尝试利用该数据库创建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

1 个答案:

答案 0 :(得分:1)

# Load files. file_names <- list.files(pattern=".txt") # Extract gene lists. gene.lists <- lapply(file_names, function(f) { scan(file=f, what=character()) }) # Name the entries in the list. names(gene.lists) <- file_names names(gene.lists) # Initiate an empty list and matrix for storing output of loop. genes.overlap <- list() nfiles <- length(gene.lists) mx.overlap.count <- matrix(NA,nrow=nfiles) # Generate contrasts: contrasts <- combn(nfiles,2) # Loop to determine intersection: for (i in 1:dim(contrasts)[2]){ list1 <- contrasts[1,i] list2 <- contrasts[2,i] g1 <- gene.lists[[list1]] g2 <- gene.lists[[list2]] comparison_name <- paste(names(gene.lists[list1]),names(gene.lists[list2]),sep="_") genes.overlap[[i]] <- intersect(g1, g2) names(genes.overlap)[i] <- comparison_name b <- length(genes.overlap[[i]]) mx.overlap.count[i] <- b } # You can index into a list like a df with the $ operator. genes.overlap$List.txt_List1.txt 表中,不需要attacker_id作为外键,因为它是主键。 我认为您想将attacker_battles链接到player_id表。因此,使用player作为外键。