2013-02-14 113 views
0

以下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 
+0

你是如何保存你的heirachy? - 看到你的選擇這個問題http://stackoverflow.com/questions/4048151/what-are-the-options-for-storing-hierarchical-data-in-a-relational-database – 2013-02-14 23:02:02

+0

嵌套集模型 – 2013-02-14 23:08:12

+0

我認爲所有你需要做的是添加'AND node.cid ='(無論cid是藍色汽車的ID) – cha 2013-02-15 00:38:50

回答

0

我覺得你一直在這得太多 - 讓子樹是關於嵌套集合

的simplist操作
SELECT * 
FROM categories 
WHERE lft BETWEEN bluecarleftvalue AND bluecarrightvalue 
ORDER BY lft ASC 
+0

基本上是的。但我需要計數產品。 – 2013-02-15 10:56:27

+0

類別和產品之間的鏈接是什麼? – 2013-02-15 20:22:39