-- get records with wrong parents
select *
from test
where
parent_id is not null
and not exists (
select id from test as parents where parents.id = test.parent_id
);
-- delete records with wrong parents
delete test.*
from test
left join test as parents on parents.id = test.parent_id
where test.parent_id is not null and parents.id is null;
select * from test;
-- add foreign key to prevent missing parents
alter table test add foreign key (parent_id) references test(id);