Ayooma Y
Ayooma Y

Reputation: 11

Error 1215: cannot add foreign key constraint in my SQL

I have the parent table which is gym_member, and I have the child which is medical_history.

In gym_member table there are two primary key which are gm_id and student_id.

In medical history table there are one primary which is mh_id, and I want to add a foreign key which is student_id but it show me this error.

ALTER TABLE `hct_gym`.`medical_history` 

ADD CONSTRAINT `student_id`

  FOREIGN KEY (`student_id`)

  REFERENCES `hct_gym`.`gym_member` (`student_id`)

  ON DELETE NO ACTION

  ON UPDATE NO ACTION;

Operation failed: There was an error while applying the SQL script to the database.

ERROR 1215: Cannot add foreign key constraint

SQL Statement:

ALTER TABLE `hct_gym`.`medical_history` 

ADD CONSTRAINT `student_id`

  FOREIGN KEY (`student_id`)

  REFERENCES `hct_gym`.`gym_member` (`student_id`)

  ON DELETE NO ACTION

  ON UPDATE NO ACTION

I want to know where is the problem?

Upvotes: 1

Views: 566

Answers (1)

DanielFo1.
DanielFo1.

Reputation: 39

Check if column medical_history.student_id contains values which are not contained in gym_member.student_id

That would contradict the constraint before /while it is being created.

Upvotes: 2

Related Questions