我有3个表(mysql)
PRODUCT_ID, 标题
CATEGORY_ID, PARENT_ID, 标题
PRODUCT_ID, CATEGORY_ID
类别树的深度未知。 有没有办法知道一个查询哪些类别有类别等有产品?
答案 0 :(得分:0)
是的,试试:
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为我们提供了树的传递闭包,pc给了我们树的叶子。
答案 1 :(得分:0)
我想有更好的方法可以做到这一点 - 但这应该有效:
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)