0

我有三个与以下关系相关的表:

"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 个广告的代理机构。这可能吗?非常感谢!

4

3 回答 3

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
于 2013-01-06T13:40:10.833 回答
1

SQL小提琴

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
于 2013-01-06T13:46:04.567 回答
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
于 2013-01-06T13:43:19.337 回答