请任何人帮我添加外键(亲子关系船) 我有两个表课程和课程主题课程主题有2列课程代码和课程名称和课程主题我有2列课程代码和主题代码现在我的目标是,如果我或更新课程表即(课程代码)它应该反映在课程主题,如果我在课程主管中删除,除非在课程主题中删除,否则不应删除。
我的课程表结构
Field Type Collation Attributes Null Default Extra Action
id int(11) No None AUTO_INCREMENT Browse distinct values Change Drop Primary Unique Index Fulltext
course_code varchar(255) latin1_swedish_ci No Browse distinct values Change Drop Primary Unique Index Fulltext
course_name varchar(255) latin1_swedish_ci Yes NULL Browse distinct values Change Drop Primary Unique Index Fulltext
课程主题
Field Type Collation Attributes Null Default Extra Action
id int(11) No None AUTO_INCREMENT Browse distinct values Change Drop Primary Unique Index Fulltext
course_code varchar(255) latin1_swedish_ci Yes NULL Browse distinct values Change Drop Primary Unique Index Fulltext
subject_code varchar(255) latin1_swedish_ci Yes NULL Browse distinct values Change Drop Primary Unique Index Fulltext
答案 0 :(得分:0)
您可以使用 DELETE CASCADE ON UPDATE CASCADE
CREATE TABLE IF NOT EXISTS `coursemaster` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`course_code` varchar(255) DEFAULT NULL,
`course_name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `index-1` (`course_code`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
INSERT INTO `coursemaster` (`id`, `course_code`, `course_name`) VALUES
(1, '001', 'French'),
(2, '009', 'English');
CREATE TABLE IF NOT EXISTS `course_subject` (
`id` int(11) NOT NULL AUTO_INCREMENT,
` course_code` varchar(255) DEFAULT NULL,
` subject_code` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `FK_1_idx` (` course_code`),
CONSTRAINT `FK_1` FOREIGN KEY (` course_code`) REFERENCES `coursemaster` (`course_code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
INSERT INTO `course_subject` (`id`, ` course_code`, ` subject_code`) VALUES
(1, '009', '4554');