Abdul Balogun
Abdul Balogun

Reputation: 13

foreign key constraint error mysql

im trying to create a database for a website that handles university classes but am having trouble in my sql

ER DIAGRAM SHOWN BELOW

er diagram link

"user" being the student

"class" being the classes

"has" being the classes that the student currently has

"wants" being the classes that that the student doesnt have but wants

I wrote queries to create the 4 tables "has" "wants" "user" and "class" but im getting errors

CREATE TABLE Class
(
ClassName varchar(255),
Professor_Name varchar(255),
Start_Time varchar(10),
End_Time varchar(10),
Course_Number varchar(20),
Section_Number varchar(20),
Days varchar(10),
PRIMARY KEY(Course_Number,Section_Number))
;

Now before creating table 'has' and 'wants' make sure user table is already created, as both these tables will take the reference from user table.

CREATE TABLE User
(
Email VARCHAR(255),
first_name VARCHAR(255),
last_name VARCHAR(255),
password VARCHAR(255),
PRIMARY KEY (Email)
);

Now we will create tables has and wants

CREATE TABLE has
(
Email VARCHAR(255),
Course_Number VARCHAR(20),
Section_Number VARCHAR(20),
PRIMARY KEY (Email, Course_Number, Section_Number),
FOREIGN KEY (Email) REFERENCE User (Email),
FOREIGN KEY (Course_Number) REFERENCES Class (Course_Number),
FOREIGN KEY (Section_Number) REFERENCES Class (Section_Number)
);

Similarly creating table wants

CREATE TABLE wants
(
Email VARCHAR(255),
Course_Number VARCHAR(20),
Section_Number VARCHAR(20),
PRIMARY KEY (Email, Course_Number, Section_Number),
FOREIGN KEY (Email) REFERENCE User (Email),
FOREIGN KEY (Course_Number) REFERENCES Class (Course_Number),
FOREIGN KEY (Section_Number) REFERENCES Class (Section_Number)
);

for some reason on the "wants" and "has" table im getting the error "cannot add foreign key constraint" im using mysql, the types are the same so im not sure why its not working, the "user" and "class" tables are fine but for some reason the other 2 im getting that error?

Upvotes: 0

Views: 58

Answers (1)

jose_bacoy
jose_bacoy

Reputation: 12684

This question is about a syntax error:

Change this:

FOREIGN KEY (Course_Number) REFERENCES Class (Course_Number),
FOREIGN KEY (Section_Number) REFERENCES Class (Section_Number)

To:

FOREIGN KEY (Course_Number, Section_Number) 
  REFERENCES Class (Course_Number, Section_Number)

Upvotes: 1

Related Questions