Home  >  Article  >  Database  >  MySQL外键创建失败的解决

MySQL外键创建失败的解决

WBOY
WBOYOriginal
2016-06-07 17:16:051095browse

创建persons:CREATE TABLE `persons` ( `id_p` int(11) NOT NULL AUTO_INCREMENT, `lastname` varchar(10) DEFAULT NULL, `fi

创建persons:
CREATE TABLE `persons` (
  `id_p` int(11) NOT NULL AUTO_INCREMENT,
  `lastname` varchar(10) DEFAULT NULL,
  `firstname` varchar(10) DEFAULT NULL,
  `address` varchar(50) DEFAULT NULL,
  `city` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id_p`)
);

再创建表orders:
CREATE TABLE `orders` (
  `id_o` int(11) NOT NULL AUTO_INCREMENT,
  `orderno` int(11) NOT NULL,
  `id_p` int(11) NOT NULL,
  PRIMARY KEY (`id_o`),
  FOREIGN KEY (`id_p`) REFERENCES `persons` (`id_p`)
);


用show create table orders语句,查询orders的信息发现,外键并没有创建成功。查了一些资料,,终于找到了原因。mysql默认创建的表是MyISAM类型的,需要将表的类型指定为innodb:


CREATE TABLE `orders` (
  `id_o` int(11) NOT NULL AUTO_INCREMENT,
  `orderno` int(11) NOT NULL,
  `id_p` int(11) NOT NULL,
  PRIMARY KEY (`id_o`),
  FOREIGN KEY (`id_p`) REFERENCES `persons` (`id_p`)
) ENGINE=InnoDB;


不过这时提示以下错误:
ERROR 1005 (HY000): Can't create table 'test.orders' (errno: 150)
将persons表的类型也指定为innodb就OK了。

总结一下外键创建失败的几种情况:
1.外键和被引用外键类型不一样,比如integer和double
2.找不到要被引用的列
3.表的字符编码不一样
4.数据引擎类型不一致,比如innodb和myisam

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn