以下SQL代碼工作正常,但無法選擇/過濾類別。帶來所有類別。按子節點過濾產品數
舉個例子,
Cars (20) (root)
---> Blue cars (12)
----------> Ford (2)
----------> Bmw (9)
----------> Dodge (1)
---> Red cars (9)
----------> Xxxx (9)
---> Black cars (1)
----------> Yy (1)
如何選擇只有藍色轎車的範疇。 (與子節點)
如何更改此代碼的SQL代碼可以完成?
我想要的結果如下。 (如果我選擇一輛藍色轎車類)
---> blue cars (12)
----------> ford (2)
----------> bmw (9)
----------> dodge (1)
這是SQL代碼...
SELECT
parent.cid,
parent.title,
(SELECT COUNT(parent2.cid) FROM categories AS parent2 WHERE parent.lft > parent2.lft AND parent.rgt < parent2.rgt) AS depth,
COUNT(products.cat_id) AS total
FROM categories AS node,
categories AS parent,
products
WHERE
node.lft BETWEEN parent.lft AND parent.rgt
AND node.cid = products.cat_id
GROUP BY parent.cid having depth <= 5
ORDER BY parent.lft
你是如何保存你的heirachy? - 看到你的選擇這個問題http://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database – 2013-02-14 23:02:02
嵌套集模型 – 2013-02-14 23:08:12
我認爲所有你需要做的是添加'AND node.cid ='(無論cid是藍色汽車的ID) – cha 2013-02-15 00:38:50