当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL添加外键时报错:1215 Cannot add the foreign key constraint的解决方法

MySQL添加外键时报错:1215 Cannot add the foreign key constraint的解决方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

香火兄弟,超时空湮灭,ddb-216

前言

这篇文章主要涉及到在数据创建表时,遇到error 1215 (hy000): cannot add foreign key constraint 问题方面的内容,对于在数据创建表时,遇到同样问题感兴趣的同学可以参考一下。

一、问题的提出

创建两个表:  

     product:  商品表

     sealer:  供货商表

相应的sql如下:

product表:

drop table if exists `product`; 
create table `product` ( 
 `id` bigint(20) unsigned not null auto_increment, 
 `name` varchar(20) not null comment 'product name', 
 `price` float(10,3) not null, 
 `description` varchar(20) default null, 
 `count` int(11) not null default '0', 
 `sid` int(11) not null, 
 primary key (`id`), 
 unique key `id_index` (`id`) using hash, 
 unique key `sid_index` (`sid`) using hash 
) engine=innodb default charset=utf8; 

sealer表:

drop table if exists `sealer`; 
create table `sealer` ( 
 `id` bigint(20) unsigned not null auto_increment, 
 `name` varchar(30) not null, 
 `city` varchar(255) default null, 
 `created_time` datetime default null, 
 `updated_time` datetime default null, 
 `level` int(11) not null default '0', 
 `description` varchar(40) default null, 
 primary key (`id`), 
 unique key `id_index_1` (`id`) using hash 
) engine=innodb auto_increment=5 default charset=utf8; 

接下来我们需要关联product.sid 至 sealer.id,进行父子表的主外键关联。

二、碰到错误

在创建外键之时,使用的sql和碰到错误信息如下:

alter table `product' add constraint `sid_ref` foreign key (`sid`) references `sealer` (`id`) on delete no action on update no action 

碰到的错误信息如下:

  
无法正确的插入外键约束。

3、问题分析

主外键更多的是某表的主键与子表的某个列进行关联,要求是具备相同的数据类型和属性,问题会不会出现在这里?

      要求: 具备相同的数据类型和约束

      发现:   unsigned,数字的字符长度不一致。

4、解决的办法

修改product.sid中的数据类型,添加unsigned和字段的长度,将其设置为相同即可。

   

总结

之所以出现1215的问题,是由于主外键之间的数据类型不一致造成的,以后类似问题,皆可按此处理。以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流。谢谢大家对移动技术网的支持。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网