MySQL多对多关系计数查询

时间:2014-05-07 10:37:45

标签: mysql

我有三张桌子

|TYPE      |  |REL_TABLE  |  |PRODUCT    |  
|----------|  |-----------|  |-----------|
|Id        |  |Id         |  |Id         |
|Title     |  |TypeId     |  |Name       | 
|CategoryID|  |ProductId  |  

正如您所看到的,关系是TYPE.id - > REL_TABLE.TypeID和PRODUCT.Id - > REL_TABLE.ProductId

我需要的是CategoryID以及每个CategoryID有多少Product.Name

2 个答案:

答案 0 :(得分:0)

只需要JOINCOUNT结果:

   SELECT t.CategoryID,
          COUNT(*)
    FROM TYPE as t
    LEFT JOIN REL_TABLE as r on t.Id = r.TypeId
         JOIN PRODUCT as p on p.id = r.ProductId
GROUP BY t.CategoryID

答案 1 :(得分:0)

简单join and count将与group by

一起使用
select t.categoryid, count(p.name)
from type t inner join rel_table rt on
t.id=rt.typeid inner join product p on
rt.productid=p.id
group by t.categoryid