gpt4 book ai didi

mysql - MySQL添加外键失败(errno 150)

转载 作者:IT王子 更新时间:2023-10-28 23:53:11 24 4
gpt4 key购买 nike

我已经阅读了许多其他关于在尝试添加外键 copnstraint 时收到 MySQL errno 150 的帖子,但是我还没有找到解决方案。我希望我没有做一些愚蠢的事情。我做了一个简单的测试用例。

  1. 两个表都是 InnoDB。

  2. 两个表都是 UTF-8。

  3. 两列都是 int(11) 无符号的(使 color_id NOT NULL 没有区别)。 (编辑:我错了关于这个,这是解决方案)

    这是我的两张 table :

表格小部件:

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;

表格颜色:

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.

我是不是在做一些荒唐可笑的事情?

最佳答案

color_id 不是unsigned 并且有一个DEFAULT NULL。列类型必须相同。

关于mysql - MySQL添加外键失败(errno 150),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16866318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com