【发布时间】:2017-02-07 01:30:27
【问题描述】:
我已经阅读了许多其他关于在尝试添加外键 copnstraint 时收到 MySQL errno 150 的帖子,但是我还没有找到解决方案。我希望我没有做一些愚蠢的事情。我做了一个简单的测试用例。
-
两个表都是 InnoDB。
-
两个表都是 UTF-8。
-
两列都是 int(11) 无符号的(使 color_id(编辑:我错了,这是解决方案)NOT NULL没有区别)。这是我的两张桌子:
表widgets:
CREATE TABLE `widgets` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL DEFAULT '',
`color_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
表colors:
CREATE TABLE `colors` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(10) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
我刚刚创建了这些表,没有内容。当我尝试添加外键约束以将 widgets.color_id 链接到 colors.id 时,会发生这种情况:
mysql> ALTER TABLE `widgets` ADD FOREIGN KEY (`color_id`) REFERENCES `color` (`id`);
ERROR 1005 (HY000): Can't create table 'production.#sql-7b1_2dd7' (errno: 150)
我要补充一点,我也无法使用我选择的 GUI 工具——OSX 上的 Sequel Pro——。尝试创建外键关系时,我收到相同的错误消息。
SHOW ENGINE INNODB STATUS 返回:
130531 17:23:06 Error in foreign key constraint of table production/#sql-7b1_2c80:
FOREIGN KEY (`color_id`) REFERENCES `colors` (`id`): Cannot find an index in
the referenced table where the referenced columns appear as the first columns,
or column types in the table and the referenced table do not match for constraint.
我是不是在做一些非常愚蠢的事情??
【问题讨论】:
标签: mysql foreign-keys