我有两张 table 。 类别和项目的表名称。我想列出带有项目数量的类别。
类别表:
id | parent | catname | catpath
1 0 A 1
2 0 B 2
3 1 A1 1,3
4 3 A11 1,3,4
5 2 B1 2,5
6 0 C 6
...
项目表:
id | catid | title
1 1 title1
2 1 title2
3 3 title3
4 4 title4
5 4 title5
6 3 title6
7 5 title7
我想要这样的打印类别: print catname (itemcount = 自己的商品数 + 子类别的商品数)
A (4) /*<- sub category's item count + own item count*/
A1 (1)
A11 (2)
B (1)
B1 (1)
更新: SQLFIDDLE
最佳答案
您可以执行此操作,因为类别表中有完整路径。荣誉。因此,您不需要递归查询:
select c.catname, count(ic.catid) as cnt
from categories c left outer join
(select i.*, c.catname, c.catpath
from items i join
categories c
on i.catid = c.id
) as ic
on concat(ic.catpath, ',') like concat(c.catpath, ',%')
group by c.catname;
这使用 like
来遍历层次结构。 ,
的原因是 1 与 10 不匹配。
关于php - 递归类别下的项目计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21368655/