我在尝试向具有现有表外键的表中添加列时收到错误消息。下面是两个失败的 SQL 语句:
ALTER TABLE current_teams ADD COLUMN master_team_id INT,
ADD FOREIGN KEY fk_master_team_id(master_team_id) REFERENCES master_teams(id) ON DELETE CASCADE;
ALTER TABLE current_teams ADD COLUMN player_id INT,
ADD FOREIGN KEY fk_player_id(player_id) REFERENCES players(id) ON DELETE CASCADE;
我得到的错误是:错误代码:1215。无法添加外键约束
当运行 innodb 时,更详细的消息说:
2016-02-03 17:22:43 0x3210 Error in foreign key constraint of table lod/#sql-1d58_6:FOREIGN KEY fk_master_team_id(master_team_id) REFERENCES master_teams(
id
) ON DELETE CASCADE: Cannot resolve table name close to: (id
) ON DELETE CASCADE
奇怪的是,在其他表上,添加完全相同的外键工作正常。这些语句运行没有问题:
ALTER TABLE team_scouting ADD COLUMN master_team_id INT,
ADD FOREIGN KEY fk_master_team_id(master_team_id) REFERENCES master_teams(id) ON DELETE CASCADE;
ALTER TABLE team_scouting ADD COLUMN player_id INT,
ADD FOREIGN KEY fk_player_id(player_id) REFERENCES players(id) ON DELETE CASCADE;
SHOW CREATE TABLE masterteams
结果如下:
'CREATE TABLE `master_teams` (
`team_name` varchar(45) DEFAULT NULL,
`owner_name` varchar(45) DEFAULT NULL,
`max_salary` double DEFAULT NULL,
`penalty` int(11) DEFAULT ''0'',
`username` varchar(10) DEFAULT NULL,
`password` varchar(25) DEFAULT NULL,
`rights` varchar(10) DEFAULT NULL,
`email` varchar(100) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=16 DEFAULT CHARSET=latin1'
仅在此“current_teams”表上添加列/外键失败。任何帮助都会很棒!谢谢。
最佳答案
您的 master_teams
表不是 InnoDB 表,因此 InnoDB 引擎“无法解析”表名。尝试像这样更新它:
ALTER TABLE master_teams ENGINE = InnoDB;
正如 Barmar 在评论中所说,constraint names do need to be globally unique .如果您不指定名称,MySQL 将为您补一个:
If the
CONSTRAINT
symbol
clause is given, the symbol value, if used, must be unique in the database. A duplicate symbol will result in an error similar to:ERROR 1005 (HY000): Can't create table 'test.#sql-211d_3' (errno: 121).
If the clause is not given, or a symbol is not included following theCONSTRAINT
keyword, a name for the constraint is created automatically.
关于MySQL 外键错误代码 1215,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35188946/