mySQL计数表有效

时间:2015-06-24 07:51:39

标签: mysql sql database

myTable

基本上我有一个表名myTable,里面有Name,Class,我想像下表那样对它们进行排序,每个名称的数量和1,2,3s的数量。下面是代码我目前有,但它可以处理少量条目,如果表格有20,000行,则需要很长时间才能执行。

Select DISTINT(Name),
       (Select count(*) from `myTable` d1 where d1.Name = dd.Name and Class=1),
       (Select count(*) from `myTable` d2 where d2.Name = dd.Name and Class=2),
       (Select count(*) from `myTable` d3 where d3.Name = dd.Name and Class=3)
from `myTable` dd
Order by Name;

3 个答案:

答案 0 :(得分:2)

这是经典的条件聚合:

Select Name,
       sum(case when Class = 1 then 1 else 0 end),
       sum(case when Class = 2 then 1 else 0 end),
       sum(case when Class = 3 then 1 else 0 end)
from myTable
group by Name

答案 1 :(得分:0)

使用条件计数执行GROUP BY

select Name,
       count(case when class = 1 then 1 end),
       count(case when class = 2 then 1 end),
       count(case when class = 3 then 1 end)
from `myTable`
group by Name;

注意: DISTINCT不是列上的函数,它适用于整个选定的行。 (如果将列名放在括号内,则无关紧要。)

select distinct(col1), col2, ...

相同
select distinct col1, col2, ...

也与

相同
select distinct col1, (col2), ...

答案 2 :(得分:0)

你可以转动它:

SELECT t.Name,
    SUM(if(t.Class=1,1,null)) as Class1,
    SUM(if(t.Class=2,1,null)) as Class2,
    SUM(if(t.Class=3,1,null)) as Class3
FROM myTable t
GROUP BY t.Name