如何用MySQL中的子查询表达count(distinct)?

时间:2012-07-11 18:51:49

标签: mysql count subquery distinct

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

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(不同)得到的结果不匹配。

使用子查询编写计数(不同)的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

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

如果你想在field1中获得符合一组条件{table_a}的table_a的不同值的数量,那么你实际上并不需要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,因此查询可以返回多行,每行都有自己的计数。