Maison > base de données > tutoriel mysql > MySQL外键创建失败的解决

MySQL外键创建失败的解决

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Libérer: 2016-06-07 17:16:05
original
1136 Les gens l'ont consulté

创建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

Étiquettes associées:
Déclaration de ce site Web
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Tutoriels populaires
Plus>
Derniers téléchargements
Plus>
effets Web
Code source du site Web
Matériel du site Web
Modèle frontal