dovs36921 2014-01-26 20:17
浏览 30

递归类别下的项目数

I have two table. Tables name of categories and items. I want to list category with item count.

categories 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

....

items table:

id | catid | title
1    1       title1
2    1       title2
3    3       title3
4    4       title4
5    4       title5
6    3       title6
7    5       title7

And I want print categories like this: print catname (itemcount = own item count + sub category's item count)

A (4)   /*<- sub category's item count + own item count*/
   A1 (1)
   A11 (2)
B (1)
   B1 (1)

UPDATE: SQLFIDDLE

  • 写回答

1条回答 默认 最新

  • douhan9467 2014-01-26 20:22
    关注

    You can do this because you have the full path in the categories table. Kudos. So, you don't need a recursive query:

    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;
    

    This uses like to traverse the hierarchy. The reason for the , is so 1 doesn't match 10.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题