试图制作外键但MySql不允许我,有什么办法吗?

时间:2013-10-03 08:35:28

标签: php mysql sql

我有这3张桌子

CREATE TABLE IF NOT EXISTS `enrollment` (
  `STUDENT_NUM` varchar(10) NOT NULL,
  `SUBJECT_NUM` varchar(10) NOT NULL,
  `UNITS` int(10) NOT NULL,
  `DAYS` varchar(50) NOT NULL,
  `TIME_START` time NOT NULL,
  `TIME_END` time NOT NULL,
  `ROOM_ID` int(11) DEFAULT NULL,
  `PRELIM` float(10,2) DEFAULT NULL,
  `MIDTERM` float(10,2) DEFAULT NULL,
  `FINALS` float(10,2) DEFAULT NULL,
  `FINAL_GRADE` float(10,2) DEFAULT NULL,
  `SEMESTER` varchar(50) NOT NULL,
  `SCHOOL_YEAR` varchar(50) NOT NULL,
  `DATE_ADDED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`STUDENT_NUM`,`SUBJECT_NUM`),
  KEY `SUBJECT_NUM` (`SUBJECT_NUM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `subjects` (
  `SUBJECT_NUM` varchar(10) NOT NULL,
  `EMPLOYEE_NUM` varchar(10) NOT NULL,
  `SUBJECT_TITLE` varchar(100) DEFAULT NULL,
  `DEPARTMENT` varchar(100) DEFAULT NULL,
  `UNITS` int(10) NOT NULL,
  `DAYS` varchar(50) NOT NULL,
  `TIME_START` time NOT NULL,
  `TIME_END` time NOT NULL,
  `room_id` int(11) DEFAULT NULL,
  `SEMESTER` varchar(50) NOT NULL,
  `SCHOOL_YEAR` varchar(50) NOT NULL,
  `COUNT` int(10) DEFAULT NULL,
  `STATUS` varchar(50) DEFAULT NULL,
  `FLAG` varchar(50) NOT NULL,
  `DATE_ADDED` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`SUBJECT_NUM`),
  UNIQUE KEY `SUBJECT_NUM` (`SUBJECT_NUM`),
  KEY `EMPLOYEE_NUM` (`EMPLOYEE_NUM`),
  KEY `EMPLOYEE_NUM_2` (`EMPLOYEE_NUM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

CREATE TABLE IF NOT EXISTS `room` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `room` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `room` (`room`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=13 ;

我要做的是从注册中获取字段ROOM_ID并使主题外键和引用成为来自房间的ID ... ROOM_ID不能是唯一的......

我收到此错误

#1452 - Cannot add or update a child row: a foreign key constraint fails (`enrollmentdb`.`#sql-277_164`, CONSTRAINT `#sql-277_164_ibfk_3` FOREIGN KEY (`ROOM_ID`) REFERENCES `room` (`ID`))

当我使用这个SQL命令时:

ALTER TABLE enrollment
ADD FOREIGN KEY (room_id)
REFERENCES room(ID)

3 个答案:

答案 0 :(得分:1)

如果正常工作,请尝试以下代码:

ALTER TABLE enrollment
 ADD CONSTRAINT ROOM_ID_fk
 FOREIGN KEY(ROOM_ID)
 REFERENCES room(ID);

谢谢!

答案 1 :(得分:0)

room_id在您的表格中大写。尝试:

ALTER TABLE enrollment
ADD FOREIGN KEY (ROOM_ID)
REFERENCES room(ID)

答案 2 :(得分:0)

将'room_id'替换为'ROOM_ID'