I\'ve got a sort of tree like thing going on in my MySQL database.
I have a database that has categories, and each category has a subcat. I\'m keeping all the catego
I'm assuming you know how to get the ID number and that's not the point of the question. Also, parent_id should also be a FK referencing id, and I would use NULL for the topmost layer, not 0.
If your top-most categories have at most one level of sub-category, you can use this query to get all Toys:
SELECT *
FROM items
WHERE items.category_id IN (SELECT id FROM categories
WHERE categories.parent_id = 1
OR categories.id = 1);
If your categories can have nested sub-categories, you'll have to use a stored procedure and call it recursively. Pseudocode:
Procedure getItemsInCategory
Input: @category_id integer
Output: items rows
{
For each item in (SELECT *
FROM items
WHERE items.category_id = @category_id):
return the row;
For each id in (SELECT id
FROM categories
WHERE categories.parent_id = @category_id):
return the rows in getItemsInCategory(id);
}