I have a list of items in MySQL, connected through a column ‘parent_id’.
Let’s assume the columns are: id, name, parent_id
If one of my users deletes an item high in the hierarchy, I need to delete all of its children. So, two part question:
1) Is there an effective and efficient MySQL call that will return ID’s for all items where its parent no longer exists?
2) In PHP, I’m thinking I can get these orphaned ID’s from MySQL into an array, then run a foreach loop and delete each?
Much thanks for your help.
I guess what the original author had in mind was something in the lines of hierarchical queries.
Unfortunately, MySQL does not have native support for hierarchical queries (unlike, for example Oracle, where you could use
CONNECT BYto achieve what you want).Probably the easiest way to remove all orphans would be to execute a query like:
This would yield you all rows from
tablewhere their parent doesn’t exist.Pair this with a PHP script that keeps executing the query and deleting any results, and after a couple of iterations your table should be free of orphans (this whole thing can probably be merged into one DELETE statement you could just execute in a while loop).
You need to execute the select-delete multiple times because of transitivity — consider a situation where an orphan is parent to another record; with the first iteration you’d remove the first orphan, making the next record in chain an orphan.
Also, make sure you explicitly skip the head of your hierarchy, otherwise you’ll end up with an empty table (as the head is, by definition, an orphan).