MySQL 外键错误代码 1215

标签 mysql foreign-keys

我在尝试向具有现有表外键的表中添加列时收到错误消息。下面是两个失败的 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 CONSTRAINTsymbol 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 the CONSTRAINT keyword, a name for the constraint is created automatically.

关于MySQL 外键错误代码 1215,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35188946/

相关文章:

php - 仅选择页面上链接的相关新闻项(多一二多关系)

mysql - 错误 1241 (21000) : Operand should contain 1 column(s) on simple insert

mysql - CakePHP saveAll 更新或插入相关数据

postgresql - 如果我想节省空间,是否必须创建代理键?

mysql - 在 MySQL 中设置外键时,ON DELETE 和 ON UPDATE 是什么意思?

java - Eclipselink/ Derby : Foreign Key Constraint

ruby-on-rails - Rails 迁移后没有 PostgreSQL 外键

mysql 组最大值行

mysql - 使 spring boot + oauth2 与 MySQL 一起工作

MySQL 外键限制未保存