如何将聚合查询与不同联接结合在一起?

时间:2019-03-18 02:05:27

标签: mysql sql

我一直在研究this SO postthis 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;

结果:

enter image description here

和:

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;

结果:

enter image description here

您可以看到列和列的数据类型匹配。我想将它们组合成一个查询,并同时显示Agents计数和Certs计数,因为这是结果集中唯一的两个列值。

如何完成?

2 个答案:

答案 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)

您可以通过JOINCOUNT 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的需要,并且省去了对输出的每一行进行两次子查询计数的过程。