MySQL数据库无法添加外键

标签 mysql database

我在向我的 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/

相关文章:

php - 即使成功提交后,值也不会从 php 表单插入 MySQL 表单

mysql - 如何将 GROUP_CONCAT 添加到我的 UNION 查询?

php - 从 mysql 中选择单值

php - Phalcon - 我如何使用 Phalcon 模型执行 SELECT IN 子查询?

java - Hibernate 急切地获取需要很长时间

mysql - 如何使用 N :M relationship in MySQL? 创建表

mysql - 在 Rails 应用程序中设置 MySQL

mysql - 如何在 MySQL 中设计消息/评论表?

mysql - 哪一个是正确的?

mysql - 为不同的 id sqlite 选择前 1 行