[英]Adding Foreign Key Fails in MySQL (errno 150)
I've read many other posts about receiving MySQL errno 150 when trying to add a foreign key copnstraint, however I haven't found a solution yet. 在尝试添加外键copnstraint时,我已经阅读了很多关于接收MySQL errno 150的帖子,但是我还没有找到解决方案。 I hope I'm not doing something stupid.
我希望我不做一些愚蠢的事情。 I made a simple test case.
我做了一个简单的测试用例。
Both columns are int(11) unsigned (making color_id
NOT NULL
doesn't make a difference).
两列都是int(11)无符号(使color_id
( EDIT: I WAS WRONG ABOUT THIS, AND THIS WAS THE SOLUTION ) NOT NULL
没有区别)。
( 编辑:我对此错了,这就是解决方案 )
Here are my two tables: 这是我的两个表:
Table widgets
: 表格
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;
Table colors
: 表
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;
I just created these tables, there is no content. 我刚刚创建了这些表,没有内容。 When I try to add a foreign key constraint to link widgets.color_id to colors.id, this happens:
当我尝试添加外键约束以将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)
I'll just add that I haven't been able to use my GUI tool of choice -- Sequel Pro on OSX -- either. 我只是补充一点,我无法使用我选择的GUI工具 - 在OSX上的Sequel Pro - 或者。 I get the same error message when trying to create a foreign key relationship.
尝试创建外键关系时,我收到相同的错误消息。
SHOW ENGINE INNODB STATUS
returns this: 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.
Am I doing something ridiculously stupid?? 我做了一些可笑的傻事吗?
color_id
is not unsigned
and has a DEFAULT NULL
. color_id
不是unsigned
并且具有DEFAULT NULL
。 The column types must be identical. 列类型必须相同。
Its almost always a case of type mismatch between the primary key and the foreign key. 它几乎总是主键和外键之间类型不匹配的情况。
Some tips to help in most cases: 在大多数情况下可以提供一些帮助:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.