Question

Here's the script

    ALTER TABLE `candycorn`.`bb_users` 
    ADD CONSTRAINT `pf_minecraftusername`
    FOREIGN KEY (`pf_minecraftusername`)
    REFERENCES `candycorn`.`bb_profile_fields_data` (`pf_minecraftusername`)
    ON DELETE NO ACTION
    ON UPDATE NO ACTION;

and the error description

    ERROR 1452: Cannot add or update a child row: a foreign key constraint fails  
    (`candycorn`.<result 2 when explaining filename '#sql-4e4_1785d'>, CONSTRAINT
    `pf_minecraftusername` FOREIGN KEY (`pf_minecraftusername`) REFERENCES 
    `bb_profile_fields_data` (`pf_minecraftusern)

if somebody could, would you explain what I'm missing out here?

Was it helpful?

Solution

The constraint that you are trying to add isn't satisfied by some data already in the tables. This can be because a value in bb_users table isn't found in the corresponding column (pf_minecraftusername) in bb_profile_fields_data.

If you have to add the constraint to tables with data already in them, you have to clean up the tables by hand first. Alternatively, you can empty the tables (with truncate, or by making the tables afresh after doing a "drop database"), then add the constraint, and then run whatever scripts you have to put data in the tables.

Of course, if this is a production system, you'll need to do more complex data fixing before you can successfully add the constraint.

Finally, I suggest that you make a dummy copy of the database with no data at all and add the constraint there, just to check that the constraint is properly specified. You don't want to be barking up the wrong tree.

OTHER TIPS

ALTER TABLE tablename with NOCHECK ADD CONSTRAINT [FK_1] FOREIGN KEY ([Column name]) REFERENCES restaurants([column name])

It seems data is already present in table.. So You need to modify table using above query.. No need to recreate table nd data

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top