如何改进包含子查询的SELECT语句?

时间:2015-04-08 14:11:33

标签: mysql select subquery

我做了这个SELECT,但我认为它可以改进。有谁知道如何才能让它变得更好?

 SELECT  SUBSTRING_INDEX(acctEmail, '@', -1) as Domain, 
        (SELECT count(*) FROM accounts 
            WHERE acctType = 'A' AND SUBSTRING_INDEX(acctEmail, '@', -1) = Domain
            GROUP BY SUBSTRING_INDEX(acctEmail, '@', -1)
        ) as qtdAlias,
        (SELECT count(*) FROM accounts 
            WHERE acctType = 'C' AND SUBSTRING_INDEX(acctEmail, '@', -1) = Domain
            GROUP BY SUBSTRING_INDEX(acctEmail, '@', -1)
        ) as qtdContas,
        (SELECT count(*) FROM accounts 
            WHERE acctType = 'L' AND SUBSTRING_INDEX(acctEmail, '@', -1) = Domain
            GROUP BY SUBSTRING_INDEX(acctEmail, '@', -1)
        ) as qtdListas,
        count(*) as Total
FROM accounts
GROUP BY Domain
ORDER BY Total DESC;

它带来以下结果:

Result

1 个答案:

答案 0 :(得分:1)

一种方法是将条件和作为

select
substring_index(acctEmail, '@', -1) as Domain, 
sum(
 case when acctType = 'A' then 1 else 0 end
) as qtdAlias,
sum(
 case when acctType = 'C' then 1 else 0 end
) as qtdContas,
sum(
 case when acctType = 'L' then 1 else 0 end
) as qtdListas,
count(*) as Total
from accounts
GROUP BY Domain
ORDER BY Total DESC;