EXPLAIN SELECT id  FROM aliai_base.base_score_summary 
WHERE   target_location = 21388 AND
target = 'courseware' AND 
score_type = 'default'; 索引是target_location + target + score_type 时,居然是type = index。
而同样的sql语句,把索引改成:target + target_location  + score_type ,(这与列的原始定义一致)
居然是type = ref

解决方案 »

  1.   

    复合索引中的字段顺序要与where语句中的条件字段相匹配
      

  2.   

    复合索引,索引的顺序与where后条件顺序相一致的。
      

  3.   

    where条件中的顺序是无所谓的,mysql优化器会自动选择,只要你的索引的最左列都出现在where中,type应该是ref的,只有在扫描整个索引的情况下type才是index
      

  4.   

    WHERE中的顺序并没有关系啊。MYSQL会自动优化。贴一下你的explain select ..
    和 show index from base_score_summary
      

  5.   

    show index from base_score_summary
    --------------------------------------------------------------------
    Table       Non_unique  Key_name Seq_in_index Column_name
    base_score_summary 0 PRIMARY     1               id             A 1353
    base_score_summary 0 TARGET     1               TARGET         A 1
    base_score_summary 0 TARGET     2               TARGET_LOCATION A 135
    base_score_summary 0 TARGET     3               SCORE_TYPE     A 1353
      

  6.   

    EXPLAIN SELECT id FROM aliai_base.base_score_summary 
    WHERE target_location = 21388 AND
    target = 'courseware' AND 
    score_type = 'default'; 
    结果:id select_type table type possible_keys key key_len ref rows Extra
    1 SIMPLE base_score_summary ref TARGET TARGET 768 const 1380 Using where; Using index
      

  7.   

    9楼的索引是target + target_location + score_type
    现在把索引修改成 target_location  + target + score_type,再explain结果:id select_type table type possible_keys key key_len ref rows Extra
    1 SIMPLE base_score_summary index TARGET_LOCATION TARGET_LOCATION 2304 1411 Using where; Using index
      

  8.   

    贴出此时的show index 以供分析。
      

  9.   

    你的target_location字段类型是什么,如果是varchar,会因为target_location = 21388不走索引,出现你描叙的这个问题