mysql添加外键错误150_在MySQL中添加外键失败(错误150)

bd96500e110b49cbb3cd949968f18be7.png

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. I hope I'm not doing something stupid. I made a simple test case.

Both tables are InnoDB.

Both tables are UTF-8.

Both columns are int(11) unsigned (making color_id NOT NULL doesn't make a difference). (EDIT: I WAS WRONG ABOUT THIS, AND THIS WAS THE SOLUTION)

Here are my two tables:

Table 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:

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:

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. I get the same error message when trying to create a foreign key relationship.

SHOW ENGINE INNODB STATUS returns this:

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. The column types must be identical.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值