【问题标题】:error: Error Code: 1215. Cannot add foreign key constraint [duplicate]错误:错误代码:1215。无法添加外键约束[重复]
【发布时间】:2021-12-09 23:36:46
【问题描述】:
DROP DATABASE IF EXISTS steelers;
CREATE DATABASE steelers;

-- select the database
USE steelers; 
   
-- Create the table 'defense'       
CREATE TABLE defense (
  defense_id int(11) NOT NULL AUTO_INCREMENT,
  player_position varchar(5) DEFAULT NULL,
  player_jersey_number int(11) DEFAULT NULL,
  player_first_name varchar(45) DEFAULT NULL,
  player_last_name varchar(45) DEFAULT NULL,
  player_id int(11)  DEFAULT NULL,
PRIMARY KEY (defense_id),
KEY player_id_idx (player_id),
CONSTRAINT c_id 
FOREIGN KEY (player_id) 
REFERENCES players (player_id) 
ON DELETE NO ACTION ON UPDATE NO ACTION)
ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8;

CREATE TABLE players (
  player_id int(11) NOT NULL AUTO_INCREMENT,
  player_jersey_number int(11) DEFAULT NULL,
  player_first_name varchar(45) DEFAULT NULL,
  player_last_name varchar(45) DEFAULT NULL,
  player_position varchar(5) DEFAULT NULL,
  player_age int(11) DEFAULT NULL,
  player_weight int(11) DEFAULT NULL,
  player_college varchar(45) DEFAULT NULL,
  player_height int(11) DEFAULT NULL,
  player_experience int(11) DEFAULT NULL,
  PRIMARY KEY (player_id))
  ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=utf8;
Error Code: 1215. Cannot add foreign key constraint

【问题讨论】:

    标签: mysql foreign-keys


    【解决方案1】:

    首先创建桌面玩家。然后创建引用玩家的桌面防御。创建表的顺序很重要。

    或者,以任意顺序创建所有表,然后根据需要 ALTER TABLE 添加外键约束。

    【讨论】:

      猜你喜欢
      • 2016-10-27
      • 2016-05-01
      • 2018-11-10
      • 2013-07-15
      • 1970-01-01
      • 2018-05-13
      相关资源
      最近更新 更多