0

When I execute the following SQL query:

CREATE TABLE course
(
   course_id varchar( 7 ) ,
   title varchar( 50 ) ,
   dept_name varchar( 20 ) ,
   credits numeric( 2, 0 ) ,
   PRIMARY KEY ( course_id ) ,
   FOREIGN KEY ( dept_name ) REFERENCES department
);

I get the following error:

MySQL said: Documentation

1215 - Cannot add foreign key constraint 

Any insights to help fix this issue ?

3 Answers 3

1

You have not included field from parent table to refer.

It should be:

FOREIGN KEY ( dept_name ) REFERENCES department( dept_name )
Sign up to request clarification or add additional context in comments.

Comments

0

The reference should be like REFERENCES TABLE( COLUMN_NAME )

FOREIGN KEY ( dept_name ) REFERENCES department( dept_name )

It will then look like

CREATE TABLE course
(
   course_id varchar( 7 ) ,
   title varchar( 50 ) ,
   dept_name varchar( 20 ) ,
   credits numeric( 2, 0 ) ,
   PRIMARY KEY ( course_id ) ,
   FOREIGN KEY ( dept_name ) REFERENCES department( dept_name )
);

Comments

0

You need to specify which column in your referenced table to match. Your query should look like this:

CREATE TABLE course
(
   course_id varchar( 7 ) ,
   title varchar( 50 ) ,
   dept_name varchar( 20 ) ,
   credits numeric( 2, 0 ) ,
   PRIMARY KEY ( course_id ) ,
   FOREIGN KEY ( dept_name ) REFERENCES department ( dept_name )
);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.