So, let's assume I've a MySQL DB with the following tables:
Product
Category
What's the best way to query the DB in order to get all products going down from a certain category id. For instance, if I've a tree of sub-categories where the base category id = 1
how can I get all the products under the subcategories of id =1
for an undetermined number of sub-categories.
I could do this:
SELECT * FROM `Product` WHERE category_id IN (
SELECT `id` FROM `Category` WHERE parent_id = 1
)
However it only works for the direct children of category id = 1
and not for the 2nd to n level children.
Thank you.
Edit
Some people suggested to read a blog article about this, I had a look at that article on the past also, and I made this sqlfiddle:
http://sqlfiddle.com/#!2/be72ec/1
As you can see on the query, even the simplest method they teach, to get a tree of categories doesn't output anything. What am I missing? The other methods have the same issue.
Thank you.
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `Category` ADD INDEX `category_idx_parent_id_id` (`parent_id`,`id`);
SELECT
*
FROM
`Product`
WHERE
EXISTS (
SELECT
1
FROM
`Category`
WHERE
(
`Category`.parent_id = 1
)
AND (
`Product`.category_id = `Category`.`id`
)
)