Jesse
Jesse

Reputation: 1495

Can't create foreign key

I'm trying to add a foreign key to an existing table, and was having issues. I figured that I had an error in my syntax, so I updated my hibernate.cfg.xml file to auto-update.

As it turns out, hibernate had the same error. Here's my SQL to add the foreign key:

alter table pbi add index FKEA3F7BDE9BAB051 (FK_idP), add constraint FKEA3F7BDE9BAB051 foreign key (FK_idP) references p (idP)

and the error is:

Cannot add or update a child row: a foreign key constraint fails (`db`.`#sql-6f8_3`, CONSTRAINT `FKEA3F7BDE9BAB051` FOREIGN KEY (`fk_idP`) REFERENCES `p` (`idP`))

Can anyone think of a reason why this would fail?

Upvotes: 0

Views: 264

Answers (1)

ChssPly76
ChssPly76

Reputation: 100776

This error means that constraint can not be applied because there are existing records that would violate it.

In your case, pbi table has rows whose FK_idP column has a value for which there are no matching records with that value in idP column of p table.

Upvotes: 3

Related Questions