获取MySQL中给定类别的子类别下的项目数

时间:2010-12-15 09:35:50

标签: mysql nested-sets

假设我们有这个表

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?
  )        

1 个答案:

答案 0 :(得分: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;

从而结束了我的答案。 我希望它有效,我也希望你能清理我的混乱(在优化我所写的内容方面)