【问题标题】:How to count two relation at the same time without subquery如何在没有子查询的情况下同时计算两个关系
【发布时间】:2015-09-16 05:37:37
【问题描述】:

假设表 A 与表 B 和表 C 有很多关系。我想实现 A.id,count(B.id),count(C.id) 结果。我怎样才能在不使用子查询的情况下得到它?

【问题讨论】:

    标签: mysql join count


    【解决方案1】:

    您可以通过在 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)

    【讨论】:

    • 谢谢,我完全忘记了在累积函数中允许使用distinct! ◕‿◕
    • 我会的。 SE不允许立即接受答案!
    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-27
    • 2020-08-09
    • 1970-01-01
    • 2013-10-30
    • 2021-11-12
    相关资源
    最近更新 更多