1.版本

1)操作系统

 cat /etc/issue
cat /etc/issue
CentOS release 6.6 (Final)
Kernel \r on an \m

 cat /proc/version
cat /proc/version
Linux version 2.6.32-504.el6.x86_64 (mockbuild@c6b9.bsys.dev.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-11) (GCC) ) #1 SMP Wed Oct 15 04:27:16 UTC 2014

2)mysql数据库版本

mysql --version
MySQL  Ver 14.14 Distrib 5.1.73, for redhat-linux-gnu (x86_64) using readline 5.1


2.问题描述

2.1 发现问题

  今天在个mysql库下建表,报如下错误:

ERROR 1005 (HY000): Can't create table 'test.test4' (errno: 150)
建表语句如下:

CREATE TABLE `test4` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(100) NOT NULL,
 `user_id` int(11) NOT NULL,
 CONSTRAINT `FK_TEST_ID` FOREIGN KEY (`id`) REFERENCES `test3` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


3. 原因分析

3.1 perror 查看错误代码

perror 150
MySQL error code 150: Foreign key constraint is incorrectly formed
其实原因很简单,外键字段和应用字段类型不一致,所以导致报错

3.2 验证

1)创建test3表(id 列类型指定varchar)

CREATE TABLE test3 (
  id varchar(10) DEFAULT NULL,
  name varchar(20) DEFAULT '0',
  KEY  (id)) engine=innodb;
2)创建test4表,并指定外键(test4表id列类型为int)
CREATE TABLE `test4` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `title` varchar(100) NOT NULL,
 `user_id` int(11) NOT NULL,
 CONSTRAINT `FK_TEST_ID` FOREIGN KEY (`id`) REFERENCES `test3` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
报错如下:

ERROR 1005 (HY000): Can't create table 'test.test4' (errno: 150)
3) 创建test4表,建表后alter创建外键

CREATE TABLE `test4` (
 `id` int(11) NOT NULL,
 `title` varchar(100) NOT NULL,
 `user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
alter table test4 add constraint FK_TEST_ID foreign key(id) REFERENCES test3(id);
ERROR 1005 (HY000): Can't create table 'test.#sql-1ce4_5589' (errno: 150)
上面是5.1.73 版本的报错,5.6下报错如下:

ERROR 1215 (HY000): Cannot add foreign key constraint

##上面的过程验证了我们的判断


4 解决方案

   修改为相同字段类型外键即可创建成功。







Logo

更多推荐