Here’s my category structure:
• Department
• Category
• Sub-Category
Here’s my database:

I want to display 6 random products from a specific department. So for example, when a user goes to view a department page I want all products in that department only. The problem I’m having is I cannot figure out a way to get only the department, for some reason I can only get the products from Category … I need to go one more level.
Here’s my SQL:
SELECT *
FROM products p
LEFT JOIN products_categories pc
ON p.product_id = pc.product_id
LEFT JOIN categories c
ON pc.category_id = c.category_id
WHERE c.category = 119
ORDER BY RAND()
LIMIT 6
119 would be the department id, but my query comes up empty because I cannot go that far down.
EDIT
I created an SQLFiddle to make things easier for everyone … very cool tool 😉
http://sqlfiddle.com/#!2/964ed/3
EDIT I’m thinking I need to explain better
So I have my categories three deep; Department, Category, and Sub-Category. The department has no products tied to it, all the products are tied to the sub-categories. Since my products aren’t tied directly to my department, how the heck can I make a query that will retrieve everything under a department? I’m trying to get everything under Firearms since that has the most products. When I query using Firearms id (119) I get nothing? But when I use one of the Sub-Categories id, I get results? So, I’m guessing I need to do some type of sub select or something, but not sure. Hopefully that clears things up 🙂
EXPECTED RESULTS
Using 119, which is the category_id for firearms, I would like to get the following records:
(143, 131, 'single-shot')
(144, 131, 'semiautomatic')
(145, 131, 'bolt-action')
(146, 131, 'pump & lever action')
(171, 130, 'bolt-action')
(174, 136, 'safe')
(178, 130, 'single-shot')
(179, 130, 'pump & lever action')
(180, 130, 'semiautomatic')
(182, 181, 'shotgun ammunition')
(183, 181, 'rimfire ammunition')
(184, 181, 'centerfire ammunition')
(185, 181, 'handgun ammunition')
(186, 120, 'cooking')
I found a site that explains exactly what I’m looking for:
http://code-slim-jim.blogspot.com/2010/06/mysql-find-grandparentsgrandchildren.html
SQL Fiddle:
http://sqlfiddle.com/#!2/964ed/97