我在向我的 MySQL 数据库添加一些外键约束时遇到问题。例如,在这个 Register 表(用于记录学生出勤的 Attendance Register 表)中,我希望将 fk_unit_id 和 fk_student_id 作为引用 Unit 和 Student 中的主键的外键。
注册表:
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(course_code) 一起工作,后者是一个 VARCHAR(4),所以我想知道它是否可能不喜欢使用 auto_incremented 主键作为外键??
编辑
我收到错误代码 #1215 - 无法添加外键限制
任何帮助将不胜感激!
最佳答案
Student 和 Unit 表中的主键都配置了 ZEROFILL,但 Register 表中引用它们的列没有配置。外键列的属性必须与它们在外部表中引用的列完全匹配。
我建议您将 Register 创建更改为如下:
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)
);
我会建议其他优化和更改,但它们超出了所发布问题的范围。
关于MySQL数据库无法添加外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29834029/