php - 递归类别下的项目计数

标签 php mysql recursive-query

我有两张 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/

相关文章:

php - MySQL 查询不工作 - 没有错误

php - SELECT INTO OUTFILE 不起作用?

mysql - 时间相关连接

MySQL 列表查询等于多个值

SQL 查询获取给定日期的有效数据

sql - 需要将递归 CTE 查询转换为索引友好查询

php - 实现消息队列的最佳方式

php - 6 个月后将用户状态从 0 更改为 1

sql - 递归关系SQL错误

php - 如何使用 strtotime 在特定时间从数据库中添加一个值作为分钟