mysql下
select   *  from   log  group by Id order by LoginTime
这个语句需要建立索引
我建立2个索引 分别是id  和   LoginTime
有人说建立复合索引 (id,LoginTime)我仍选择2个索引 只是不知道明确的原因???

解决方案 »

  1.   

    建立复合索引好,mysql每次查询都只会选择一个对查询效率最高的索引,建立复合索引相当于同时使用了两个索引。
      

  2.   


    请注意是
    group by Id order by LoginTime 不是 where id=?  and LoginTime =?好像说不通?
      

  3.   

    语句先走 按id分组
    在按loginTime排序数据量大的时候和数据量小的时候 建立索引两种方式效率是不同的
      

  4.   

    你可以explain sql查看一下执行索引的情况。
      

  5.   

    2个索引 分别是id  和   LoginTime 
    也走了索引的   
      

  6.   

    select   *  from   log  group by Id order by LoginTime这种语法格式本身就是非标准的。 转化为标准的后你就会清晰的看出来应该如何做索引了。
      

  7.   

    实际上还是走的是 (id, loginTime)
      

  8.   

    mysql> show index from a;
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
    | Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
    | a     |          0 | PRIMARY  |            1 | id          | A         |           2 | NULL     | NULL   |      | BTREE      |         |
    | a     |          1 | ids_ab   |            1 | a           | A         |           2 | NULL     | NULL   | YES  | BTREE      |         |
    | a     |          1 | ids_ab   |            2 | id          | A         |           2 | NULL     | NULL   |      | BTREE      |         |
    | a     |          1 | idx_id   |            1 | id          | A         |           2 | NULL     | NULL   |      | BTREE      |         |
    | a     |          1 | idx_a    |            1 | a           | A         |           2 | NULL     | NULL   | YES  | BTREE      |         |
    +-------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
    5 rows in set
    mysql> explain 
    select * from a group by id order by a;
    +----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------+
    | id | select_type | table | type  | possible_keys | key    | key_len | ref  | rows | Extra           |
    +----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------+
    |  1 | SIMPLE      | a     | index | NULL          | ids_ab | 9       | NULL |   12 | Using temporary |
    +----+-------------+-------+-------+---------------+--------+---------+------+------+-----------------+
    1 row in set
      

  9.   

    select * from a group by id order by a;这句转成标准的SQL语句是什么?