现在有一张表,数据量可能就几十万。
我需要统计其中某种类型的数据,比如select count(*) from TABLE where type='A'
问题是这样的,我的type可能是A、B、C、D中的任何一种。select count(*) from TABLE where type='A'
select count(*) from TABLE where type='B'
select count(*) from TABLE where type='C'
select count(*) from TABLE where type='D'
我是这样好呢?还是
select type from TABLE
然后再程序中计算好呢?

解决方案 »

  1.   

    这样好
    select type,count(*) from TABLE group by type
      

  2.   

    select type,count(*) from TABLE group by type order by null 
      

  3.   

    select sum(if(type='A',1,0)),sum(if(type='b',1,0)),sum(if(type='c',1,0)),...
    from tt 
      

  4.   

    select type,count(*) from TABLE group by type;
      

  5.   

    在表上创建TYPE字段的索引就可以了。然后用 #2楼,#4楼 的语句就行了。#3楼 的这种方法是全表扫描,效率会很差。如果你只是想查A的数量,则就用你自己的 select count(*) from TABLE where type='A', 如果传到程序中来统计,效率会比较差 1)大量的数据传输 2)全表记录都要传,无法利用索引
      

  6.   

    索引是建了的,忘了说一个条件,就是group by之类的都被禁用了。
    我也想可能传数据到程序再统计的数据量会很大。现在唯一的办法是读4次数据库,每次单独count
      

  7.   


    GROUP BY 禁了?很奇怪的设置啊。 是如何禁的呢?如果不用GROUP BY,那就把这四个查询UNION ALL起来,但单纯从效率上并没有什么提高。虽然把4次数据库访问改成一次访问。select 'A' as type,count(*) from TABLE where type='A'
    UNION ALL
    select 'B', count(*) from TABLE where type='B'
      

  8.   


    最好还是决定访问4次数据库了。
    我们用了一个框架,这个框架是分表的,也就是一张表被分成很多个子表。无法用group by,exist()之类的.虽然我这张表是单表,但框架限制死了。