MySQL - 如何按组计算总数

时间:2013-01-06 13:36:11

标签: mysql join count group-by

我有三个表连接以下关系:

"agency" 1-n "agent" 1-n "ad" 
(agency has many agents and each agent has many ads)

我希望按代理机构获取广告计数列表,如下所示:

agency_name   |   ad_count
---------------------------
agency 1      |     15
agency 2      |     25
agency 3      |     0

即使展示0个广告的代理商也会出现。这可能吗?非常感谢!

3 个答案:

答案 0 :(得分:1)

由于你没有提供确切的表结构,我不得不猜一点

select agency.agency_name, 
       count(ad.id) as ad_count
from agency 
left outer join agent on agency.id = agent.agency_id
left outer join ad on ad.id = agent.ad_id
group by agency.agency_name

答案 1 :(得分:1)

SQL Fiddle

select agency.agency_name, count(ad.id)
from agency
left join agent on agent.agency_id = agency.id
left join ad on ad.agent_id = agent.id
group by agency.agency_name

答案 2 :(得分:0)

试试这个:

SELECT a.agencyname, IFNULL(b.adcnt, 0) adcount  
FROM agency 
LEFT JOIN (SELECT a.agencyid, SUM(adcnt) adcnt 
           FROM agent a 
           INNER JOIN (SELECT agentid, COUNT(agentid) adcnt 
                       FROM ad 
                       GROUP BY agentid
                      ) b ON a.agentid = b.agentid 
           GROUP BY agencyid) b ON a.agencyid = b.agencyid