Mysql – Can’t define a foreign key

foreign keyMySQL

In MySQL I've two tables:

Monitors:
    Id: INT PRIMARY KEY NOT NULL AUTOINCREMENT
    GroupId: INT NULL
    ....

MonitorGroups:
    Id: INT PRIMARY KEY NOT NULL AUTOINCREMENT
    Name: VARCHAR(50)

I need to define this constraint:

ALTER TABLE Monitors ADD CONSTRAINT monitor_group_fk FOREIGN KEY (GroupId) REFERENCES MonitorGroups (Id);

But I get the following error:

ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`zm`.`#sql-475_1c237`, CONSTRAINT `monitor_group_fk` FOREIGN KEY (`GroupId`) REFERENCES `MonitorGroups` (`Id`))

At the moment there's no record in MonitorGroups table and GroupId of rows of table Monitors are not set. I need it to be legal. In another words, I need MySQL to keep track of the field GroupId of table Monitor only if it's set. I would like to define the constraint as:

ALTER TABLE Monitors ADD CONSTRAINT monitor_group_fk FOREIGN KEY (GroupId) REFERENCES MonitorGroups (Id) ON UPDATE CASCADE ON DELETE SET NULL;

so that if a group id (Id field) changed in table MonitorGroups, MySQL change it automatically in table Monitors and if a group was deleted from table MonitorGroups, MySQL automatically set GroupId of corresponding rows in table Monitors to null.
What's wrong and how to reach this goal?

Best Answer

There is da ROW in the table Monitors, which has a value in the column "GroupId" for which the foreign key constraint fails (=it does not exist in the table MonitorGroups). Check if there is a GroupId whithout a corresponding Id-Value in table Groups.