I have some data:
| id | parent_id | topic_id |
|---|---|---|
| 1 | 1 | |
| 2 | 1 | 1 |
| 3 | 2 | |
| 4 | 3 | 2 |
parent_id has FK to id.
I'm trying to delete data by topic_id - as U see, one row is referencing to another row which both are to be deleted. But sometimes this fails due to a FK violation. It is makes it kinda hard to reproduce this situation.
How to delete them?
- begin deletion from the leafs and work upwards?
- encapsule this into transaction (right now it is in "auto-commit" mode)?
- temporarily disable FKs? Don't want that, I might corrupt data
- ...?
Managed to reproduce this. SQL:
create table test (
id bigint auto_increment primary key,
parent_id bigint null ,
topic_id bigint,
foreign key (parent_id) references test(id)
) engine=innodb;
insert into test (id, parent_id, topic_id)
values
(1, null, 1),
(2, 1, 1),
(3, 2, 1),
(4, null, 2),
(5, 4, 2);
-- select * from test;
delete from test where topic_id=1;
-- [23000][1451] Cannot delete or update a parent row: a foreign key constraint fails (`mydb`.`test`, CONSTRAINT `test_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `test` (`id`))
idis autoincremented primary key. So your scheme guarantees that the relationid > parent_idis TRUE for each non-root row. In this case you may use a trickDELETE FROM test WHERE topic_id=1 ORDER BY id DESC;. See dbfiddle.uk/idWyrsD5 But I recommend to use the solution provided by Guillaume Outters because it provides deterministic behaviour.select version();show?