按照article的说明,我希望获得一个完整的树,每个类别的深度都可以正常工作。
我也希望得到每个类别的产品数量。我尝试添加另一个COUNT(products_categories.product_id),但它搞砸了深度值。如何修改查询以获取每个类别的产品数量和深度?
products_categories
----------------------
category_id
product_id
SELECT node.name, (COUNT(parent.name) - 1) AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft
换句话说,我想结合这两个查询。
SELECT node.name, (COUNT(parent.name) - 1) AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
GROUP BY node.name
ORDER BY node.lft
SELECT parent.name, COUNT(product.name)
FROM nested_category AS node ,
nested_category AS parent,
product
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.category_id = product.category_id
GROUP BY parent.name
ORDER BY node.lft;
答案 0 :(得分:1)
我终于解决了我的问题。我结合了上面的查询,这样我就可以获得深度和产品数量。
SELECT parent.id,
parent.lft,
parent.rgt,
(SELECT COUNT(parent2.id) FROM businesscategories AS parent2 WHERE parent.lft > parent2.lft AND parent.rgt < parent2.rgt) AS depth,
COUNT(b_c.business_id) AS bcount
FROM businesscategories AS node,
businesscategories AS parent,
businesses_categories AS b_c,
WHERE node.lft BETWEEN parent.lft AND parent.rgt AND node.id = b_c.category_id
GROUP BY parent.id having depth > 0
ORDER BY parent.lft