0

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?

1 Answer 1

1

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.

10
  • 1
    yes, you're right. as i said, i need to validate existence of rows in table Monitors with GroupId NULL. I know that some database managers support nullable foreign keys, but I'm not sure whether MySQL does it too and how it does.
    – hamidi
    Commented Jun 2, 2018 at 12:31
  • NULL is not the problem here?
    – TheHe
    Commented Jun 2, 2018 at 12:55
  • hmm, see, I need no Id of table MonitorGroups be zero or null. I may allow a row in table Monitors have GroupId of zero, but if assigned another value, it should assign from table MonitorGroups. Is it possible?
    – hamidi
    Commented Jun 2, 2018 at 13:03
  • I added a row in table Groups with Id zero and this resolved the problem. But I need to know how can I avoid this.
    – hamidi
    Commented Jun 2, 2018 at 14:59
  • 1
    " should set to NULL (identical to 0 for me)" 0 is not identical to NULL in SQL. Commented Jun 17, 2018 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.