Quantcast
Viewing all articles
Browse latest Browse all 1957

Strange Foreign key error (3 replies)

Hi
I'm using foreign key since 15 years ago with other SGDB
But i'm a little new with mysql

So there is a trouble that does not happen on other SGBD
Got 2 tables 1 parent and 1 child

CREATE TABLE TBPARENT (
`COLP1` VARCHAR(10) NOT NULL,
`COLP2` INT NOT NULL,
PRIMARY KEY (`COLP1`, `COLP2`));

With 2 rows:
INSERT INTO `TBPARENT` (`COLP1`, `COLP2`) VALUES ('A', '0');
INSERT INTO `TBPARENT` (`COLP1`, `COLP2`) VALUES ('A', '1');

CREATE TABLE `TBCHILD` (
`COLCH1` INT NOT NULL,
`COLCH2` VARCHAR(10) NOT NULL,
`COLCH3` VARCHAR(45) NULL,
PRIMARY KEY (`COLCH1`));

With 1 row :
INSERT INTO `TBCHILD` (`COLCH1`, `COLCH2`, `COLCH3`)
VALUES ('100', 'A', 'ABC');

Now let's create a FK on COLCH2 references by TBPARENT(COLP1) like this :

ALTER TABLE `TBCHILD`
ADD INDEX `FK_CHILD_PARENT_idx` (`COLCH2` ASC);
ALTER TABLE `TBCHILD`
ADD CONSTRAINT `FK_CHILD_PARENT`
FOREIGN KEY (`COLCH2`)
REFERENCES `TBPARENT` (`COLP1`)
ON DELETE NO ACTION
ON UPDATE CASCADE;

Now try this :
DELETE FROM TBPARENT WHERE COLP2=0

It must works because after that, a row of TBPARENT containing 'A' in COLP1 will still exist.

But i've got :
Error Code: 1451. Cannot delete or update a parent row: a foreign key constraint fails (`TBCHILD`, CONSTRAINT `FK_CHILD_PARENT` FOREIGN KEY (`COLCH2`) REFERENCES `TBPARENT` (`COLP1`) ON DELETE NO ACTION ON UPDATE CASCADE) 0.062 sec

Why ??

Viewing all articles
Browse latest Browse all 1957

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>