mysql 执行计划解释

mysql execution plan explanation

有如下查询

select count(*)
from my_table my_t
where my_t.c1 = '3' and my_t.c2 = '123'

这个 table 在 (c1, c2) 上有索引并且这两列都有 not null 约束。

其执行计划:

# id, select_type, table, type, possible_keys,    key, key_len,         ref, rows, Extra
   1,      SIMPLE,  my_t,  ref,        my_idx, my_idx,     157, const,const,    1, Using where; Using index

它用在哪里,但用于什么目的?由于两列都不为空,因此索引肯定会包含所有记录,这对于计算它们是必要的。

我是不是漏掉了什么?

documentation 说:

Using index

The column information is retrieved from the table using only information in the index tree without having to do an additional seek to read the actual row. This strategy can be used when the query uses only columns that are part of a single index.

If the Extra column also says Using where, it means the index is being used to perform lookups of key values. Without Using where, the optimizer may be reading the index to avoid reading data rows but not using it for lookups. For example, if the index is a covering index for the query, the optimizer may scan it without using it for lookups.

据我上面的理解,Using index只表示读取key列中指定的索引足以获取计算结果所需的所有数据;无需读取 table 数据。它没有说明如何使用索引信息。

Using where 表示将从 key 列中提到的索引读取的值与 ref 列中指示的列或常量的值进行比较输出。 ref 列包含 const, const,因为用于比较的值是字符串常量('3''123')。