【问题标题】:One to many relation: group by column on the many side and count the rows in the one side一对多关系:在多侧按列分组并计算一侧的行数
【发布时间】:2020-08-31 22:42:32
【问题描述】:

我有两个表 A 和 B,一对多的关系(B 有 A 的外键)。现在我需要按 B 中的列分组,但要计算 A 中的行数(不同)。是否可以不使用 COUNT (distinct A.Id)

   SELECT b.column1,
         Count(*) totalGroupCount,
         Count(distinct a.id) CountOfA   -- I dont want to this for perf reason
   FROM A a JOIN B b on a.id = b.a_id
   GROUP BY b.column1

【问题讨论】:

    标签: sql postgresql join count query-optimization


    【解决方案1】:

    如果你想计算不同的值,那么count(distinct ...) 是要走的路。解决方法可能不会执行得更快。

    但是,让我建议简化您的查询:您不需要表 a 来获得您想要的结果(尤其是如果您有外键约束)。这已经足够了:

    select column1, count(*) totalgroupcount, count(distinct a_id)
    from b
    group by column1
    

    然后,您可以尝试在b(column1, a_id) 上建立索引以提高性能。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      • 2020-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-19
      相关资源
      最近更新 更多