mysql计数子表及其主表的子表

时间:2011-11-01 14:44:37

标签: mysql join

Table 1 - Category

id | name

Table 2 - subcat

id | cid(category.id) | name

Table 3 - products

id | cid(category.id) | sid(subcat.id) | name

select a.* , count(b.id) as total
         from category a left join
         subcategory b on a.id=b.cid 
         group by a.id order by a.name

这给出了每个类别的子类别数

我可以单独运行产品,这样我就可以获得每个类别的产品数量

我想要的是子类别的数量和每个类别的产品数量。如何形成查询?

它应该像catename,(子类别)的数量和(产品)的数量

2 个答案:

答案 0 :(得分:0)

因为您可能有给定类别的子类别,但没有实际列出此类子类别的产品,您可能无法得到您期望的结果......这应该同时适合您

select a.id,
       a.name, 
       BySubCat.AvailableSubCategories,
       ByProduct.ActualSubCats,
       ByProduct.ProductCount
   from
      category a

         left join
            ( select cid, count(*) as AvailableSubCategories
                 from subcat
                 group by cid ) BySubCat
            on a.id = BySubCat.cid

         left join
            ( select cid,
                     count( distinct sid ) as ActualSubCats,
                     count(*) ProductCount
                 from
                    products
                 group by
                    cid ) ByProduct
            on a.id = ByProduct.cid
  order by
     a.name

答案 1 :(得分:0)

试试这个:

select c.name,count(sc.id),count(sub.pcount)
from subcat sc
inner join
(
    select p.sid as subid, count(p.id) as pcount from Products p 
    inner join subcat sc on sc.id = p.sid
    group by p.sid
) sub
on sub.subid = sc.id
inner join Category c on c.id = sc.cid
group by sc.id,sub.pcount