获取父节点和子节点以及计数

时间:2013-10-25 15:40:32

标签: mysql sql

我根据guide from this article使用嵌套模型。

  

嵌套类别表如下。

nested_category

  

产品表如下。

product

我想获得父节点&所选级别的子节点。例如:如果选择了电视,则应显示查询。此外,还应显示每个类别中每种产品的数量。

Electronics
  Television
    Tube     (2)
    LCD      (1)
    Plasma   (2)

我写了以下查询

SELECT parent.name, count(product.product_id)
FROM nested_category AS node,nested_category AS parent,nested_category AS midpoint
LEFT JOIN product ON product.product_id=midpoint.category_id
WHERE (node.lft BETWEEN parent.lft AND parent.rgt) AND (node.lft BETWEEN midpoint.lft AND midpoint.rgt) AND midpoint.name='TELEVISIONS'
GROUP BY parent.name
ORDER BY node.lft

我得到的结果是

Results from my query

这让所有的孩子都得到了父节点正常但计数错误。 Check the SQL Fiddle here

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT parent.category_id as pid, parent.name as pname, SUM(product.product_id IS NOT NULL)
FROM
nested_category AS parent,
nested_category AS midpoint,
nested_category AS node
LEFT JOIN product ON product.category_id=node.category_id
WHERE (node.lft BETWEEN parent.lft AND parent.rgt)
AND (node.lft BETWEEN midpoint.lft AND midpoint.rgt)
AND midpoint.name='TELEVISIONS'
GROUP BY parent.category_id
ORDER BY parent.category_id;