如何在没有子查询的情况下同时计算两个关系

How to count two relation at the same time without subquery

假设 table A 与 table B 和 table C 有很多关系。我想获得 A.id,count(B.id),count(C.id) 结果。如果不使用子查询,我怎样才能得到它?

您可以通过在 count() 函数中使用 distinct 关键字来实现此目的。示例:

select
  A.id,
  count(distinct B.id),
  count(distinct C.id)
from A
  left outer join B on B.A_id = A.id
  left outer join C on C.A_id = A.id
  group by A.id;

参考:MySQL docs on count(distinct).