这里需要提醒的是:mysql的执行计划和查询的实际执行过程并不完全吻合。如何证明这一点呢?
真正的执行过程可以通过mysql的trace工具来分析。
1,针对执行2
EXPLAIN SELECT * FROM student WHERE cid=1;
这里只显示trace结果的一部分内容:
{
"considered_execution_plans": [
{
"plan_prefix": [
] /* plan_prefix */,
"table": "`student`",
"best_access_path": {
"considered_access_paths": [
{
"access_type": "scan",
"rows": 1,
"cost": 1.2,
"chosen": true
}
] /* considered_access_paths */
} /* best_access_path */,
"cost_for_plan": 1.2,
"rows_for_plan": 1,
"chosen": true
}
] /* considered_execution_plans */
},
可以看到并没有使用索引,而是进行了全表扫描。
2,下面再来看一下执行1的trace:
{
"considered_execution_plans": [
{
"plan_prefix": [
] /* plan_prefix */,
"table": "`student`",
"best_access_path": {
"considered_access_paths": [
{
"access_type": "ref",
"index": "name_cid_INX",
"rows": 1,
"cost": 1.2,
"chosen": true
},
{
"access_type": "ref",
"index": "name_INX",
"rows": 1,
"cost": 1.2,
"chosen": false
},
{
"access_type": "scan",
"cause": "covering_index_better_than_full_scan",
"chosen": false
}
] /* considered_access_paths */
} /* best_access_path */,
"cost_for_plan": 1.2,
"rows_for_plan": 1,
"chosen": true
}
] /* considered_execution_plans */
},
可以看出最终使用的索引是name_cid_INX。
王珊《数据库系统概论》(第5版)网授精讲班【教材精讲+考研真题串讲】
3,where中and条件的先后顺序对如何选择索引是无关的。因为优化器会去分析判断选用哪个索引。