I'm having a problem adding some foreign key constraints to my MySQL database. For example, in this Register table (Attendance Register table for recording students attendance) I would like to have fk_unit_id and fk_student_id as foreign keys referencing the primary keys in Unit and Student.
Register Table:
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)
);
Student table:
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)
);
Unit Table:
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)
);
For the record, the fk_course_code does work with Course(course_code) which is a VARCHAR(4), so I'm wondering if perhaps it doesn't like using an auto_incremented Primary Key as a Foreign Key??
Edit
I am getting error code #1215 - Cannot add foreign key restraint
Any help will be much appreciated!