gpt4 book ai didi

php - 尝试创建外键,但 MySql 不允许我,有什么办法吗?

转载 作者:行者123 更新时间:2023-11-29 13:32:58 25 4
gpt4 key购买 nike

我有这 3 张 table

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)

最佳答案

尝试下面的代码是否有效:

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

谢谢!

关于php - 尝试创建外键,但 MySql 不允许我,有什么办法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19154475/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com