2009-11-19 81 views
4

我有一個嵌套集模型爲我的網站在子類別中的項目等。除了一個我不能來的問題之外,它工作得很好。嵌套集模型,在類別中計數項目

+---------+-----------------------------+ 
| item_id | item_name     | 
+---------+-----------------------------+ 
|  1 | Laptop      | 
|  2 | iPod Classic 80GB   | 
|  3 | iPod Classic 160GB   | 
+---------+-----------------------------+ 
+---------+-------------+ 
| item_id | category_id | 
+---------+-------------+ 
|  1 |   4 | 
|  2 |   2 | 
|  3 |   2 | 
+---------+-------------+ 
+-------------+--------------------+-----+-----+ 
| category_id | name    | lft | rgt | 
+-------------+--------------------+-----+-----+ 
|   1 | iPod    | 1 | 6 | 
|   2 | Classic   | 2 | 3 | 
|   3 | Nano    | 4 | 5 | 
|   4 | Computers   | 7 | 8 | 
+-------------+--------------------+-----+-----+ 

使用以下查詢:

SELECT parent.name, COUNT(product.item_id) 
    FROM Category AS node, Category AS parent, Item_Category AS 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; 

提供了以下的輸出:

+-----------------+------------------------+ 
| name   | COUNT(product.item_id) | 
+-----------------+------------------------+ 
| iPod   |      2 | 
| Classic   |      2 | 
| Computers  |      1 | 
+-----------------+------------------------+ 

換句話說,將不會顯示沒有產品在他們所有領域。現在到這個問題,我想向他們展示COUNT()結果= 0.我的查詢將如何實現這一點? :)

回答

3

聽起來像是LEFT OUTER任務JOIN對我來說,就像這樣:

SELECT parent.name, COUNT(product.item_id), 
     (select count(*) from Category parent2 
     where parent.lft > parent2.lft 
      and parent.rgt < parent2.rgt) as depth 
    FROM Category parent 
    LEFT OUTER JOIN Category node 
    ON node.lft BETWEEN parent.lft AND parent.rgt 
    LEFT OUTER JOIN Item_Category product 
    ON node.category_id = product.category_id 
GROUP BY parent.name 
ORDER by node.lft 

因此,可以確保所有類別都被顯示。請注意,我不是100%確定。

編輯:添加了深度的子選擇,試試看。

編輯:刪除逗號

+0

工作就像一個魅力:) – xintron 2009-11-19 14:34:22

+0

很高興聽到這個消息。 – 2009-11-19 14:41:11

+0

有沒有可能使用此查詢同時計算子類別的深度? – xintron 2009-11-20 08:54:54