有一个表t_test(userid(int),age(int),register_time(int),sex(smallint)),一条查询语句"select userid from t_test where sex=$sex and age=$age order by register_time limit 10";对于这个查询来说,是在age,register_time,sex三列建一个联合索引效率高,还是,sex和age上建一个联合索引,register_time单独建一个索引效率好?

解决方案 »

  1.   

    对于这个sql
    alter table t_test add index(age,sex,register_time) 索引字段顺序很重要你说的其他两个索引基本对这个sql没什么用 
      

  2.   

    再有,如果是"select userid from t_test where age=$age order by register_time limit 10",这样的话,该如何建立索引呢
      

  3.   


    create index xxx on t_test (age,register_time )
      

  4.   

    我测试了下,如果对age和register_time各自单独建立一个索引也是很快的啊,这两种到底哪个更好呢,为什么,谢谢!
      

  5.   

    如果是"select userid from t_test where age=$age order by register_time limit 10"
    create index xxx on t_test(age,register_time);
      

  6.   

    理论上是复合索引更适合这个查询。但具体也要看你表中的数据分布。贴出你的 show index from t_test ;
    explain select userid from t_test where age=$age order by register_time limit 10;以供分析。
      

  7.   


    +---------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
    | Table  | Non_unique | Key_name      | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment |
    +---------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+
    | t_test |          0 | PRIMARY       |            1 | uid         | A         |      633858 |     NULL | NULL   |      | BTREE      |         |
    | t_test |          1 | idx_age       |            1 | age         | A         |           56|     NULL | NULL   |      | BTREE      |         |
    | t_test |          1 | idx_register  |            1 | registertime| A         |      633858 |     NULL | NULL   |      | BTREE      |         |
    | t_test |          1 | idx_sex       |            1 | sex         | A         |           3 |     NULL | NULL   | YES  | BTREE      |         |
    +-------------+------------+---------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+-----++----+-------------+-------------+-------+---------------+-------------+---------+------+------+-------------+
    | id | select_type | table       | type  | possible_keys | key         | key_len | ref  | rows | Extra       |
    +----+-------------+-------------+-------+---------------+-------------+---------+------+------+-------------+
    |  1 | SIMPLE      | t_test      | index | idx_age       | idx_register| 4       | NULL |   10 | Using where |
    +----+-------------+-------------+-------+---------------+-------------+---------+------+------+-------------+
      

  8.   

    很显然,你根本就没创建 create index xxx on t_test(age,register_time);这个索引。 你是如何比较哪个快的呢?因为你刚好试验了一个比较少年龄的数字。你符合这个$age的记录只有10条。你的表中一共有56个不同年龄,一共633858记录,平均分布的话,每个年龄应该11318记录。 
      

  9.   

    我查询的时候limit 10了-_-!!我的确没有建立这个复合索引,但这样也的确速度比较快啊