错误的sql性能与mysql中索引列的简单where条件

时间:2017-06-26 22:01:36

标签: mysql sql performance

我有一个非常简单的sql语句

  SELECT    `genre_application`.`genre_id`
      FROM  `genre_application`
      WHERE `genre_application`.`application_id` = 310633997

即使列上有索引也需要大约2秒钟。

{
"query_block": {
"select_id": 1,
"cost_info": {
  "query_cost": "2098202.80"
},
"table": {
  "table_name": "genre_application",
  "access_type": "index",
  "key": "PRIMARY",
  "used_key_parts": [
    "genre_id",
    "application_id"
  ],
  "key_length": "8",
  "rows_examined_per_scan": 10363019,
  "rows_produced_per_join": 1036301,
  "filtered": "10.00",
  "using_index": true,
  "cost_info": {
    "read_cost": "1890942.42",
    "eval_cost": "207260.38",
    "prefix_cost": "2098202.80",
    "data_read_per_join": "23M"
  },
  "used_columns": [
    "genre_id",
    "application_id"
  ],
  "attached_condition": "(`genre_application`.`application_id` = 310633997)"
}
}

我怎样才能改善执行时间?

1 个答案:

答案 0 :(得分:3)

这是您的查询:

SELECT ID,AVG(maxScore) as avgScore
FROM (SELECT ID,TestCode,MAX(Score) as maxScore
      FROM TEST_SCORES
      WHERE TestCode in ('MCA','BRT','RTK') 
      GROUP BY ID,TestCode
     ) t
GROUP BY ID

您需要一个索引,其中SELECT ga.`genre_id` FROM `genre_application` ga WHERE ga.`application_id` = 310633997 是索引中的第一个键。最佳索引是application_id上的综合索引。请注意,索引中键的顺序很重要。