Quoted my original answer for clarity.
UPDATE 1: The problem with the table splitting is that it isn't clear that there is a fixed number of sub, sub, categories. For this to work, you would need to split into as many tables as there are subcategories, each with foreign keys back to their parent ids. Not practical if the number of sub (or sub sub) categories is dynamic.
This is a situation where I think you would benefit in changing your
table design. If you split the two tables into categories and
subcategories you could take advantage of the foreign key
functionality as described by strauberry. For example (these don't
look like tables, but hopefully this makes sense) Stuff in parentheses
is explanation:
categories
subcategories
- sub_id (primary key)
- id (foreign key referencing primary key of categories table)
- subCatName
Then when you create the categories table, you can use the ON DELETE
CASCADE option. This will mean that whenever you delete a category
from the categories table, all related subcategories in the
subcategories table will be deleted automatically for you by MySQL.
Powerful, and reduces your code, and you don't have to make sure all
deletions happen in the right tables manually. Hope that clarifies a
little.
UPDATE 2: The problem with this option is, well, it won't work :) MySQL will not allow you to subquery on the same table that you are doing the DELETE on. So what appeared at first to be a simple problem... isn't.
If you can't change the table design then you could do the following
(substitute the id you actually want to delete for
category_id_to_delete):
DELETE FROM categories
WHERE id = category_id_to_delete OR id IN (
SELECT id
FROM categories
WHERE parentID = category_id_to_delete
)
So, I did some more checking, and came across this similar question on SO MySQL: How to find all IDs of children recursively?, and the highest rated answer points to this article Managing Hierarchical Data in MySQL. That article points out the type of queries with LEFT JOINS that you need to use to select data, but doesn't explicitly cover how to delete that data. The recommended solution would be to use the queries related to adjacent sets from the article to select all the id information you need, and then in your code (php I think?) loop over those ids and construct a new query to delete them.
For example, if you are trying to delete Category 1 (id=1), your goal by looping over the ids from the LEFT JOIN query from the article would be to create another query that looks like:
DELETE FROM categories
WHERE id IN (1,3,4,5,6);
The code in this forum post also may help you as a means of doing it recursively in php: Adjacency List Model recursive deletion
I know that isn't a neat and tidy answer, but perhaps this will point you in the right direction.