现在有一个图书表,记载了图书信息,图书id为nh_id,
要求有一个图书章节表,按章节记载图书的具体信息,外键nh_id对应图书表的nh_id,同时要求如果图书表id改变,对应的章节表的外键也改变,如果图书删除,该书对应的章节也一并删除
添加外键约束为
CONSTRAINT `nh_chapter-nh` FOREIGN KEY (`nh_id`) REFERENCES `nh` (`nh_id`) ON DELETE CASCADE ON UPDATE CASCADE
其中
CONSTRAINT `nh_chapter-nh` FOREIGN KEY (`nh_id`) REFERENCES `nh` (`nh_id`)
为建立外键
ON DELETE CASCADE ON UPDATE CASCADE
为一并删除或更新
完整参考
CREATE TABLE `nh` ( `nh_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT ‘小说编号‘, `type` tinyint(2) unsigned NOT NULL COMMENT ‘类型‘, `sex` tinyint(1) unsigned NOT NULL COMMENT ‘性别[1男2女]‘, `name` varchar(100) NOT NULL COMMENT ‘名称‘, `intro` varchar(1500) NOT NULL COMMENT ‘简介‘, `words` varchar(10) NOT NULL COMMENT ‘字数‘, `author` varchar(30) NOT NULL COMMENT ‘作者‘,PRIMARY KEY (`nh_id`) ) ENGINE=InnoDB AUTO_INCREMENT=10613 DEFAULT CHARSET=utf8mb4 COMMENT=‘小说表‘; CREATE TABLE `nh_chapter` ( `chapter_id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT ‘章节编号‘, `index` int(10) unsigned NOT NULL COMMENT ‘章节编号‘, `nh_id` int(10) unsigned NOT NULL COMMENT ‘小说编号‘, `title` varchar(100) NOT NULL COMMENT ‘标题‘, `total` int(10) unsigned NOT NULL COMMENT ‘章节字数‘, `content` mediumtext NOT NULL COMMENT ‘章节内容‘, PRIMARY KEY (`chapter_id`),KEY `nh_id` (`nh_id`), CONSTRAINT `nh_chapter-nh` FOREIGN KEY (`nh_id`) REFERENCES `nh` (`nh_id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=244808 DEFAULT CHARSET=utf8mb4 COMMENT=‘小说章节表‘;