【问题标题】:How to express count(distinct) with subquery in MySQL?如何在 MySQL 中用子查询表示 count(distinct)?
【发布时间】:2012-07-11 18:51:49
【问题描述】:

查询会产生一定数量的结果。查询是:

select
count(distinct case when (A or B or C) and D then table_a.field1 else null end)
from table_a
    left join table_b on table_b.x = table_a.y
group by table_a.y
;

其中 A、B、C 和 D 是给定的条件。现在,写成这样的形式:

select
sum((select count(1) from table_b where table_b.x = table_a.y and ((A or B or C) and D) ))
from table_a
    left join table_b on table_b.x = table_a.y
group by table_a.y
;

结果与我们通过 count(distinct) 得到的结果不匹配。

用子查询写 count(distinct) 的正确方法是什么?

【问题讨论】:

    标签: mysql count subquery distinct


    【解决方案1】:

    完全不清楚为什么需要子查询。您仍然拥有 JOIN,因此子查询可能会多次“计数”相同的行。

    如果您想在table_a 中获取满足一组条件(在table_a 上)的field1 的不同值的数量,那么您实际上不需要在table_b 上使用子查询来获得它。至少,无论如何我看不到您可以使用 table_b 上的子查询获得该结果。

    这是一个返回等效结果的示例:

     select (select sum(1) as mycount
               from ( select a.field1 
                        from table_a a
                        left join table_b on table_b.x = a.y
                       where a.y = t.y
                         and ( (A or B or C) and D )
                         and a.field1 IS NOT NULL
                       group by a.field1
                    ) s
            ) as mycount
       from table_a t
      group by t.y
    

    这确实是我知道的获得与COUNT(DISTINCT expr) 等效的东西的唯一方法。你必须做一个SELECT expr FROM ... WHERE expr IS NOT NULL GROUP BY expr,然后计算它返回的行数。在这种情况下,您可以使用 COUNT(1) 或 SUM(1)。

    (我完全不确定这是否能回答你所问的问题,但这是我最好的选择。)

    (我们注意到,在您的原始查询中,您有一个 GROUP BY table_a.y,因此该查询可以返回多行,每行都有自己的计数。

    【讨论】:

      猜你喜欢
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      相关资源
      最近更新 更多