在我的数据库中,我有以下表格:
Person (
id,
name,
agentId
)
Agent (
id,
title
)
Agency (
id,
name
)
AgentAgency (
id,
agentId,
agencyId
)
我需要查询才能获得有关Person的所有信息 - >具有额外属性numberOfAgencies的代理将显示每个代理的代理商数量,并且我需要再显示一个属性agencyName,它将显示用户拥有的第一个或唯一代理商的名称(如果代理商只有1个代理商,我需要它)。
我试过这样的事但没有成功。
SELECT *, COUNT (aa.agentId) as numberOfAgencies
FROM agentAgencies as aa
LEFT JOIN agent as a ON a.id = aa.agentId
LEFT JOIN agency as ag ON aa.agencyId= ag.id
LEFT JOIN person as p ON p.id = ag.personId
GROUP BY ag.id, aa.id, p.id, a.id
例如,我希望这样的回应: PersonName John,AgencyName Cool Agency,numberOfAgencies 4
答案 0 :(得分:2)
SELECT
MAX(p.Name) PersonName,
count(a.id) NoOfAgencies,
MAX(a.name) AgencyName
FROM persons p
LEFT OUTER JOIN agent g ON g.Id=p.agentId
LEFT OUTER JOIN AgentAgency aa ON aa.agentId = g.Id
LEFT OUTER JOIN Agency a on a.id = aa.agencyId
GROUP BY a.Id