MySQL数据库无法添加外键

时间:2015-04-23 20:48:56

标签: mysql database

我在向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 - 无法添加外键约束

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

Student和Unit表中的两个主键都配置了ZEROFILL,但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)
);

我建议进行其他优化和更改,但它们超出了发布问题的范围。