I have a table F:
CREATE TABLE IF NOT EXISTS `mydb`.`table_f` (
`id_f` INT NOT NULL AUTO_INCREMENT,
`fk_1` INT(11) NOT NULL,
`fk_2` INT(11) NOT NULL,
`column_F` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id_f`),
INDEX `index2` (`fk_1` ASC, `fk_2` ASC) )
ENGINE = InnoDB
id_f | fk_1 | fk_2 | column_F
-------------------------------
1 | 1 | 1 | AA
2 | 1 | 2 | BB
3 | 1 | 2 | CC <-- "Duplicate" of row id_f=2 (but valid data)
4 | 2 | 1 | DD
And a table A:
CREATE TABLE IF NOT EXISTS `mydb`.`table_a` (
`id_a` INT NOT NULL AUTO_INCREMENT,
`fk_1` INT(11) NOT NULL,
`fk_2` INT(11) NOT NULL,
PRIMARY KEY (`id_a`),
INDEX `a_idx` (`fk_1` ASC, `fk_2` ASC) ,
CONSTRAINT `fk`
FOREIGN KEY (`fk_1` , `fk_2`)
REFERENCES `mydb`.`table_f` (`fk_1` , `fk_2`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
id_a | fk_1 | fk_2
---------------------
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
Table A has a foreign key as: [fk_1, fk_2], so I ensure that there is, at least, one record in Table F.
The problem is, I want to delete from table_f where id_f=3. But I cannot, because of the foreign key.
Also, important to notice, the duplicate on table_f is on purpose and necessary.
How can I ensure that a table has at least one row on another table, but being able to delete this row later?
ON DELETE CASCADE`? – Vérace Jan 06 '20 at 20:29F(fk_1, fk_2)was NOT defined as UNIQUE. – Akina Jan 06 '20 at 20:32table_a, just ontable_f. Even after deleting ontable_f,table_awill continue to have its foreign key – Gustavo Lopes Jan 06 '20 at 20:33table_f. The data provided in the question is valid. I just cannot delete a row ontable_f(but I can insert seamlessly) – Gustavo Lopes Jan 06 '20 at 20:35F(fk_1, fk_2)must NOT to be unique then your data is not normalized. – Akina Jan 06 '20 at 20:42(fk_1, fk_2)pair into separate table, where this pair is defined as UNIQUE. And bothAandFreferences to it. – Akina Jan 06 '20 at 21:19