2010-12-15 40 views
1
下一個給定類別的兒童類的項目數的計數

說我們有這個表獲取在MySQL

t1 
-------------------------------- 
category_id | name | lft | rgt 
-------------------------------- 
1    cat1 1  8 
2    cat2 2  3 
3    cat3 4  7 
4    cat4 5  6 

t2 
------------------------------- 
item_id | category_id 
-------------------------------- 
1   1 
2   2 
3   3 
4   4 

是否有MySQL的一種方式來獲得項目的類別有數量(包括那些屬於其子女的物品)?這樣的事情...

------------------------------- 
category_id | item_count 
-------------------------------- 
1    4 
2    1 
3    2 
4    1 

我無法連接獲取category_ids的查詢和獲取子類別數的查詢。

SELECT category_id FROM t1 WHERE <some conditions here> 

SELECT 
    COUNT(*) AS item_count, 
    category_id 
FROM 
    t2 
WHERE 
    t2.category_id IN 
    (
SELECT 
     node.category_id 
FROM 
    t1 AS node, 
    t1 AS parent 
    WHERE 
    node.lft BETWEEN parent.lft AND parent.rgt 
    AND parent.category_id = 5 <---- How do I pass the category ids of the first query 
             here? 
)   
+0

我的查詢返回奇怪的結果 - 不應該category_id 2有一個itemcount爲2? – Pimgd 2010-12-15 10:32:42

+0

更新的解決方案 - 希望它的工作原理! – Pimgd 2010-12-15 10:42:48

回答

1
SELECT a.category_id, COUNT(a.item_id) as itemcount 
FROM itemTable a 
GROUP BY a.category_id; 

所有你需要做的是找出如何添加沒有任何產品這個的人。

編輯: 好吧,所以問題是獲得一個子選擇值... 我不是SQL的專家,但我建議創建一個視圖。

SELECT category_id FROM t1 WHERE <some conditions here> 
CREATE VIEW temp AS 
SELECT 
    node.category_id as nc_id, parent.category_id as pc_id 
FROM 
    t1 AS node, 
    t1 AS parent 
WHERE 
    node.lft BETWEEN parent.lft AND parent.rgt; 

VIEW temp 
nc_id | pc_id 
1 1 
2 1 
3 1 
4 1 
2 2 
3 2 
4 3 


t2 
itemid| catid 
1 1 
2 2 
3 3 
4 4 

CREATE VIEW temp2 AS 
    SELECT 
    * 
    FROM 
    t2, temp 
    WHERE t2.category_id = temp.nc_id OR t2.category_id = temp.pc_id 

cat_id| itemid |nc_id | pc_id 
1 1 1 1 
1 1 2 1 
1 1 3 1 
1 1 4 1 
2 2 2 1 
2 2 2 2 
2 2 3 2 
3 3 3 1 
3 3 3 2 
3 3 4 3 
4 4 4 1 
4 4 4 3 

CREATE VIEW temp3 AS 
SELECT cat_id, itemid, nc_id, pc_id 
FROM temp2 
GROUP BY item_id, nc_id; 

temp3: 
cat_id| itemid |nc_id | pc_id 
1 1 1 1 
1 1 2 1 
1 1 3 1 
1 1 4 1 
2 2 2 1 
2 2 3 2 
3 3 3 1 
3 3 4 3 
4 4 4 1 

SELECT count(itemid) AS itemcount, cat_id 
FROM temp3 
GROUP BY cat_id; 

itemcount  |cat_id 
4  1 
2  2 
2  3 
1  4 

DROP VIEW temp3; 
DROP VIEW temp2; 
DROP VIEW temp; 

因此總結了我的答案。 我希望它的作品,我也希望你能清理我的爛攤子(關於優化我寫的內容)

+0

我對第一個查詢使用了一個簡單的例子。但它在現實中有一些WHERE條件。 – arvinsim 2010-12-15 09:54:17