jeudi 23 avril 2015

MySQL Database Can't Add Foreign Key

I'm having a problem adding some foreign key constraints to my MySQL database. For example, in this Register table 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,
fk_course_code VARCHAR(4) NOT NULL,
PRIMARY KEY (student_id),
CONSTRAINT FOREIGN KEY (fk_course_code) REFERENCES course(course_code)
);

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??

Any help will be much appreciated!

Looking into it more... I've now confused myself completely :( I have a chasm trap in my ERD I think...

Lecturer ---< Unit >--- Course | | ^ Register >--- Student

I cannot tell which Students are assigned to which Units/Course unless they have an entry in the register... Argh I'm getting so confused!

Aucun commentaire:

Enregistrer un commentaire