1
votes

I create four tables in mysql. But it shows the error when creating the 4th.

ERROR 1005 (HY000): Can't create table 'db.grades' (errno: 150)

I checked the name and type is right for the foreign keys. Any suggestions? Thanks.

CREATE TABLE students
(

id int unsigned not null,
first_name VARCHAR(50),
last_name VARCHAR(50),
email_address VARCHAR(50),
primary key (id)

);



-------
CREATE TABLE departments 
(
school_code enum('L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M' ),
dept_id int unsigned,
abbreviation VARCHAR(9),
dept_name VARCHAR(200),
PRIMARY KEY (school_code,dept_id)
);


----

create table courses(
school_code enum('L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M' ),
dept_id int unsigned,
course_code char(5),
name varchar(150),
primary key (school_code,course_code,dept_id)
);


-----

create table grades(
pk_grade_ID int unsigned auto_increment,
student_id int unsigned not null,
grade decimal,
school_code enum('L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M' ),
dept_id int unsigned,
course_code char(5), 
name varchar(150),
primary key (pk_grade_ID),
foreign key (student_id) references students(id),
foreign key (school_code,course_code,name) references courses (school_code,course_code,name)
);

----
1

1 Answers

1
votes

Are you sure you're last foreign key in the Grades table shouldn't reference the primary key in the Courses table (which includes dept_id instead of name):

foreign key (school_code,course_code,dept_id)
     references courses (school_code,course_code,dept_id)

This works -- http://sqlfiddle.com/#!2/451d1

BTW -- if possible, consider removing the enum column altogether. Create a lookup table instead and use that as a foreign key.