mySql外键名称问题

时间:2013-02-07 15:26:25

标签: mysql foreign-keys primary-key mysql-workbench

您好我在mysql workbench中设计了一个数据库。当我去转发工程师的时候,我得到了(错误号:121),因为我在多个表中都有相同的外键,我意识到这是不允许的。我有很多联结表,因为大多数是n:m关系。我使用复合主键(由2个外键组成)用于大多数这些连接表。我的问题是,我是否必须将这些主键重命名为与外键一起使用? 请欣赏一些帮助。

(我还没有在下面的代码中重命名外键)

CREATE  TABLE IF NOT EXISTS `mydb`.`tblStudent` (
  `StudentID` INT(6) NOT NULL AUTO_INCREMENT ,
  `Student_Firstname` VARCHAR(20) NOT NULL ,
  `Student_Lastname` VARCHAR(20) NOT NULL ,
  `DOB` DATE NOT NULL ,
  `Student_Gender` ENUM('Male','Female') NOT NULL ,
  `Student_Address1` VARCHAR(40) NOT NULL ,
  `Student_Address2` VARCHAR(22) NOT NULL ,
  `Student_Address3` VARCHAR(14) NOT NULL ,
  `Student_Phonenum` INT(10) NULL ,
  `Student_Email` VARCHAR(60) NOT NULL ,
  `Student_Password` CHAR(128) NOT NULL ,
  `Enrollment_Date` DATE NOT NULL ,
  `Graduation_Date` DATE NULL ,
  `Student_Picture` VARCHAR(100) NOT NULL ,
  `PPSN` VARCHAR(9) NOT NULL ,
  PRIMARY KEY (`StudentID`) )
ENGINE = InnoDB

CREATE  TABLE IF NOT EXISTS `mydb`.`tblIllness` (
  `IllnessID` CHAR(5) NOT NULL ,
  `Illness_Name` VARCHAR(30) NOT NULL ,
  PRIMARY KEY (`IllnessID`) )
ENGINE = InnoDB

CREATE  TABLE IF NOT EXISTS `mydb`.`tblStudentIllness` (
  `IllnessID` CHAR(5) NOT NULL ,
  `StudentID` INT(6) NOT NULL ,
  `Doctor_Name` VARCHAR(30) NOT NULL ,
  `Doctor_Phonenum` INT(10) NOT NULL ,
  `Medication` VARCHAR(40) NOT NULL ,
  `Medical_Advice` VARCHAR(250) NOT NULL ,
  PRIMARY KEY (`IllnessID`, `StudentID`) ,
  INDEX `IllnessID_idx` (`IllnessID` ASC) ,
  INDEX `StudentID_idx` (`StudentID` ASC) ,
  CONSTRAINT `IllnessID`
    FOREIGN KEY (`IllnessID` )
    REFERENCES `mydb`.`tblIllness` (`IllnessID` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT `StudentID`
    FOREIGN KEY (`StudentID` )
    REFERENCES `mydb`.`tblStudent` (`StudentID` )
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB

1 个答案:

答案 0 :(得分:1)

This compiles对我很好。一种解决方案是只删除约束名称,它们将自动为您生成。

...
CONSTRAINT 
    FOREIGN KEY (`IllnessID` )
    REFERENCES `tblIllness` (`IllnessID` )
    ON DELETE CASCADE
    ON UPDATE CASCADE,
CONSTRAINT
    FOREIGN KEY (`StudentID` )
    REFERENCES `tblStudent` (`StudentID` )
    ON DELETE CASCADE
...