0

请任何人帮我添加外键(父子关系)我有两个表课程大师和课程主题在课程大师中有2列课程代码和课程名称在课程主题中我有2列课程代码和主题代码现在我的目标是如果我或更新 coursemaster 表即(课程代码)它应该反映在课程主题中,如果我在 coursemaster 中删除它不应该删除,除非在 coursesubject 中删除。

我的课程表结构

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
4

1 回答 1

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');
于 2013-11-01T03:43:12.563 回答