1

假设我们有这张桌子

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

1 回答 1

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;

我的回答就这样结束了。我希望它有效,我也希望你能清理我的烂摊子(在优化我写的内容方面)

于 2010-12-15T09:41:23.223 回答