我一直在研究this SO post和this jooq.org post,试图弄清楚如何在 MySQL 中进行合并聚合,但是运气不佳。
这是我的2个查询:
select a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate, count(*) AS Agents
from Users u
join Agencies a
on u.AgencyID = a.ID
group by a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate
order by a.IsTestAgency, a.AgencyName;
结果:
和:
select a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate, count(*) AS Certs
from Certificates c
join Agencies a
on c.AgencyID = a.ID
group by a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate
order by a.IsTestAgency, a.AgencyName;
结果:
您可以看到列和列的数据类型匹配。我想将它们组合成一个查询,并同时显示Agents
计数和Certs
计数,因为这是结果集中唯一的两个列值。
如何完成?
答案 0 :(得分:1)
这是您想要的吗?
select a.*,
(select count(*)
from users u
where u.AgencyID = a.ID
) as users_count,
(select count(*)
from Certificates c
where c.AgencyID = a.ID
) as certificates_count
from Agencies a
order by a.IsTestAgency, a.AgencyName;
答案 1 :(得分:1)
您可以通过JOIN
到COUNT
s个表中来做到这一点:
select a.IsTestAgency, a.ID, a.AgencyName, a.CreateDate, u.Agents, c.Certs
from Agencies a
join (select AgencyID, COUNT(*) as Agents from Users group by AgencyID) u on u.AgencyID = a.ID
join (select AgencyID, COUNT(*) as Certs from Certficates group by AgencyID) c on c.AgencyID = a.ID
order by a.IsTestAgency, a.AgencyName;
这消除了在顶部查询中使用group by
的需要,并且省去了对输出的每一行进行两次子查询计数的过程。