如何计算mysql中父子类下的总项数

时间:2016-05-04 07:27:07

标签: mysql

我有两张桌子

subcategorytbl

 sub_id    sub_title     sub_parent_id
   1        For rent           0
   2        Car                1
   3        Motorcycle         1 
   4        For Sale           0 
   5        Boat               4

itemtbl

  item_id    sub_id
    1          2
    2          2  
    3          3
    4          1
    5          2
    6          5

汽车和摩托车正在出租,而船则在For Sale子类别下。因此,结果应该是这样的:

For Rent(5) 
- Car(3)
- Motorcycle(1)
For Sale(1) 
- Boat(1)

以下是我的询问:

  SELECT  count(*) as itemcount ,  sub_parent_id  from 
   subcategorytbl
  LEFT JOIN  itemtbl ON   subcategorytbl.sub_id=itemtbl.sub_id  
  GROUP BY   subcategorytbl.sub_id

2 个答案:

答案 0 :(得分:2)

您需要的是GROUP BY ... WITH ROLLUP选项:

 SELECT  count(*) as itemcount ,  sub_parent_id  from 
   subcategorytbl
  LEFT JOIN  itemtbl ON   subcategorytbl.sub_id=itemtbl.sub_id  
  GROUP BY   subcategorytbl.sub_id WITH ROLLUP

答案 1 :(得分:2)

select concat(if(a.sub_parent_id>0," - ",""), a.sub_title,'(',count(itb.it_id),')') from subcategorytbl a inner join (select sub_id as sid,sub_id as chid from subcategorytbl where sub_parent_id=0 union
select sub_parent_id as sid,sub_id as chid from subcategorytbl where sub_parent_id>0
union select sub_id as sid,sub_id as chid from subcategorytbl where sub_parent_id>0
 ) b on b.sid=a.sub_id  
 inner join (select item_id as it_id,sub_id  as itsid from itemtbl) itb on itb.itsid=b.chid 
 group by a.sub_title order by a.sub_id;

输出

For rent(5)
 - Car(3)
 - Motorcycle (1)
For Sale(1)
 - Boat(1)