views:

49

answers:

1

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?

+3  A: 

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.

ChssPly76
Yep, that was it. I had to remove the NOT NULL clause in the add column query to add the foreign key (or do a migration before adding the key)
Jesse