我在向MySQL数据库中添加一些外键约束时遇到了问题。例如,在此注册表(用于记录学生出勤率的考勤登记表)中,我希望fk_unit_id和fk_student_id作为外键引用单元和学生中的主键。
登记表:
CREATE TABLE IF NOT EXISTS register
(
fk_unit_id INT(4) NOT NULL,
fk_student_id INT(4) NOT NULL,
register_date DATE NOT NULL,
attendance CHAR(1) NOT NULL,
PRIMARY KEY (fk_unit_id, fk_student_id, register_date),
FOREIGN KEY (fk_unit_id) REFERENCES unit(unit_id),
FOREIGN KEY (fk_student_id) REFERENCES student(student_id)
);学生表:
CREATE TABLE IF NOT EXISTS student
(
student_id INT(4) ZEROFILL NOT NULL AUTO_INCREMENT,
student_first_name VARCHAR(20) NOT NULL,
student_surname VARCHAR(20) NOT NULL,
student_dob DATE NOT NULL,
student_contact_no VARCHAR(11) NOT NULL,
student_email VARCHAR(30) NOT NULL,
student_address VARCHAR(50) NOT NULL,
student_image_name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id)
);单位表:
CREATE TABLE IF NOT EXISTS unit
(
unit_id INT(4) ZEROFILL NOT NULL AUTO_INCREMENT,
unit_name VARCHAR(50) NOT NULL,
unit_day VARCHAR(10) NOT NULL,
unit_time VARCHAR (10) NOT NULL,
fk_course_code VARCHAR(4) NOT NULL,
fk_lecturer_id INT(4) NOT NULL,
PRIMARY KEY (unit_id),
FOREIGN KEY (fk_course_code) REFERENCES course(course_code),
FOREIGN KEY (fk_lecturer_id) REFERENCES lecturer(lecturer_id)
);为了记录这一点,fk_course_code确实与课程(Course_code)一起工作,这是一个VARCHAR(4),所以我想知道它是否不喜欢使用auto_incremented主键作为外键?
编辑
我得到了错误代码#1215 -不能添加外键限制。
任何帮助都将不胜感激!
发布于 2015-04-24 13:42:47
“学生”表和“单元”表中的两个主键都配置了ZEROFILL,但是引用它们的寄存器表中的列不是。外键列的属性必须与它们在外接表中引用的列完全匹配。
我建议您将登记册创建更改如下:
CREATE TABLE IF NOT EXISTS register
(
fk_unit_id INT(4) ZEROFILL NOT NULL,
fk_student_id INT(4) ZEROFILL NOT NULL,
register_date DATE NOT NULL,
attendance CHAR(1) NOT NULL,
PRIMARY KEY (fk_unit_id, fk_student_id, register_date),
CONSTRAINT `c_fk_unit_id` FOREIGN KEY (fk_unit_id) REFERENCES unit(unit_id),
CONSTRAINT `c_fk_student_id` FOREIGN KEY (fk_student_id) REFERENCES student(student_id)
);我建议还有其他的优化和修改,但它们超出了发布的问题的范围。
https://stackoverflow.com/questions/29834029
复制相似问题