[英]Cannot add foreign key constraint
I have created a database "webportal". 我创建了一个数据库“ webportal”。 and this is my "user" table script 这是我的“用户”表脚本
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) DEFAULT NULL,
`password` varchar(255) DEFAULT NULL,
`firstName` varchar(255) DEFAULT NULL,
`lastName` varchar(255) DEFAULT NULL,
`dateRegistered` DATE DEFAULT NULL,
`skypeID` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
and this one is "catalog" table script. 这是“目录”表脚本。
DROP TABLE IF EXISTS `catalog`;
create table catalog(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
and when I try to execute the second script in the command line, I get this error... 当我尝试在命令行中执行第二个脚本时,出现此错误...
ERROR 1215 (HY000): Cannot add foreign key constraint. 错误1215(HY000):无法添加外键约束。 What is wrong with this code? 此代码有什么问题?
It seems you are using a old version of MySQL, you can add a INDEX
clause to foreign key field to fix the problem: 似乎您使用的是旧版本的MySQL,可以在外键字段中添加INDEX
子句以解决此问题:
DROP TABLE IF EXISTS `catalog`;
create table `catalog`(
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`link` VARCHAR(100) NOT NULL,
`comment` VARCHAR(100) NOT NULL,
`inserDate` DATE DEFAULT NULL,
`content` longblob NOT NULL,
PRIMARY KEY (`id`),
INDEX (`user_id`),
CONSTRAINT `fk_catalog` FOREIGN KEY (`user_id`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.