0

我有这 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)
4

3 回答 3

1

如果它有效,请尝试以下代码:

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

谢谢!

于 2013-10-03T08:45:42.363 回答
0

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

ALTER TABLE enrollment
ADD FOREIGN KEY (ROOM_ID)
REFERENCES room(ID)
于 2013-10-03T08:39:38.390 回答
0

将“room_id”替换为“ROOM_ID”

于 2013-10-03T08:42:42.107 回答