1
votes

I have 3 tables (mysql)

products

product_id, title

categories

category_id, parent_id, title

products_categories

product_id, category_id

The depth of the category tree is unknown. Is there a way to know with one query which categories have categories etc. that have products?

2
With your current data model I don't believe that this is possible in MySQL. You can find alternative models for hierarchies by looking for Joe Celko's book on trees and hierarchies or from some of the links in this post: stackoverflow.com/questions/4345909/mysql-recursionTom H
Why not just do the same on all the categories - if no products than you'll won't have nothing returns from your query, but it can be done with JOIN, I'll check it nowItay P.
I use recursion to fetch first parent categories and then for each parent category fetch its subcategories etc to build the menu. But how can I know if a category doesn't have products so I don't display it?Vagelis Ouranos

2 Answers

0
votes

Yep, try :

select c1.*, c2.* from categories c1, categories c2, products_categories pc where c1.category_id = c2.parent_id and pc_category_id = c1.category_id;

c1, c2 gives us the transitive closure for your tree, pc gives us the leaves of the tree.

0
votes

I guess there is a better way to do that - but this should work:

SELECT tb1.* FROM categories AS tb1 JOIN products_categories AS tb2 ON tb1.category_id=tb2.category_id AND tb2.product_id IN (SELECT tb3.product_id FROM products AS tb3 JOIN products_categories AS tb4 ON tb3.product_id=tb4.product_id WHERE tb3.product_id=tb2.product_id)