我有2个表: shop_products 和 shop_category 。
shop_products :ID,名称,类别ID
shop_category: ID,名称,parent_id,有效。 Active可以是“ true”或“ false”。
类别的嵌套方式类似于parent> subcat> subsubcat> ...
如何获得所有父类别处于“ true”状态的产品?
我尝试使用JOIN。但是它仅采用最接近的类别,而不采用树的顶级类别。
SELECT * FROM shop_products
INNER JOIN shop_category as sc1 ON (shop_products.category_id=sc1.id)
INNER JOIN shop_category as sc2 ON (sc1.parent_id=sc2.id)
WHERE sc2.active=1
UPD: 这是sqlfiddle
我希望什么也不会得到。由于顶级类别“ Cat1”具有有效的 false
答案 0 :(得分:0)
使用以下查询:
SELECT s.* FROM shop_products as s WHERE EXISTS (
SELECT id FROM shop_category as sc WHERE sc.id = s.category_id AND EXISTS(
SELECT id FROM shop_category as sc1 WHERE sc.id = sc1.id AND sc1.active = 1
)
);