本帖最后由 zhangzhenting 于 2010-03-12 16:12:14 编辑

解决方案 »

  1.   

    有没有其他方法更高效的获取按a1,a2分组之后的个数?
    没有
    在上个帖子就说过,GROUP BY是最快的
      

  2.   

    和你的索引有关,创建 create index bbb on a(a3); 后你可以看到相反的情况。 如果需要可以进一步创建 (a3,a1,a2) 的索引。mysql> select count(*) from a;
    +----------+
    | count(*) |
    +----------+
    |  1000000 |
    +----------+
    1 row in set (0.00 sec)mysql> select count(1) from (select 1 from a where a3 between '2010-01-01 00:00:
    00' and '2010-12-31 23:59:59'  group by a1,a2) tmp;
    +----------+
    | count(1) |
    +----------+
    |    99813 |
    +----------+
    1 row in set (2.08 sec)mysql> select count(distinct a1,a2) from a where a3 between '2010-01-01 00:00:00
    ' and '2010-12-31 23:59:59';
    +-----------------------+
    | count(distinct a1,a2) |
    +-----------------------+
    |                 99813 |
    +-----------------------+
    1 row in set (2.55 sec)mysql>
    mysql> create index bbb on a(a3);
    Query OK, 1000000 rows affected (23.03 sec)
    Records: 1000000  Duplicates: 0  Warnings: 0mysql> select count(1) from (select 1 from a where a3 between '2010-01-01 00:00:
    00' and '2010-12-31 23:59:59'  group by a1,a2) tmp;
    +----------+
    | count(1) |
    +----------+
    |    99813 |
    +----------+
    1 row in set (1.50 sec)mysql> select count(distinct a1,a2) from a where a3 between '2010-01-01 00:00:00
    ' and '2010-12-31 23:59:59';
    +-----------------------+
    | count(distinct a1,a2) |
    +-----------------------+
    |                 99813 |
    +-----------------------+
    1 row in set (1.17 sec)mysql>
      

  3.   

    嗯, 加了a3索引, 确实看到效果了。两条SQL都使用 a3索引SQL1执行时间:1.656s
    SQL2执行时间:1.496s只是第一条SQL出现了 Using where; Using temporary; Using filesort。wwwwb,如果使用group by,可以对SQL1进行优化吗?
      

  4.   

    为什么一定要GROUP BY呢? GROUP BY 并不快啊。 
      

  5.   

    ACMAIN_CHM
    看你的执行结果, 电脑挺牛的啊。我还是双核电脑,2G内存, 加个索引就卡死了。
    既然group by 不快, 就不用了
      

  6.   

    我的T60 ,  CPU T7200 @ 2.00GHz 2GB memory
      

  7.   

    使用 (a3,a1,a2)索引
    sql 1: 0.875s Using where; Using index; Using temporary; Using filesort
    sql 2: 0.735s Using where; Using index