explain的type

type指的是访问类型,可以衡量sql的好坏。

The type column of EXPLAIN output describes how tables are joined

常见的type有system,const,eq_ref,ref,range,index,all。显示sql是从最好到最坏。

  • system

The table has only one row (= system table). This is a special case of the const join type.

只有一条记录。这个当然太理想了。当然它也是最快的。

  • const

The table has at most one matching row, which is read at the start of the query. Because there is only one row, values from the column in this row can be regarded as constants by the rest of the optimizer. const tables are very fast because they are read only once.
const is used when you compare all parts of a PRIMARY KEY or UNIQUE index to constant values.

const一般出现在主键索引和唯一索引上。它是至多只有一条记录匹配。

explain的type_第1张图片
按照主键id查一次就查到了。

  • eq_ref

One row is read from this table for each combination of rows from the previous tables. Other than the system and const types, this is the best possible join type. It is used when all parts of an index are used by the join and the index is a PRIMARY KEY or UNIQUE NOT NULL index.
eq_ref can be used for indexed columns that are compared using the = operator. The comparison value can be a constant or an expression that uses columns from tables that are read before this table

它也是常用于主键索引和唯一性索引。并且只有一条记录匹配。

我们用=来展示:

explain的type_第2张图片

由于后面加了and tbl_emp.name='s7',所以只有一条记录匹配。

  • ref

All rows with matching index values are read from this table for each combination of rows from the previous tables. ref is used if the join uses only a leftmost prefix of the key or if the key is not a PRIMARY KEY or UNIQUE index (in other words, if the join cannot select a single row based on the key value). If the key that is used matches only a few rows, this is a good join type.

refeq_ref不同的是,它有多条记录。

ref也是一种索引查询。

我们为tbl_emp表再插入一条数据:


explain的type_第3张图片

where name='ocean'当然用了我们建的索引,并且有多条记录。

  • range

Only rows that are in a given range are retrieved, using an index to select the rows. The key column in the output row indicates which index is used. The key_len contains the longest key part that was used. The ref column is NULL for this type.
range can be used when a key column is compared to a constant using any of the =, <>, >, >=, <, <=, IS NULL, <=>, BETWEEN, LIKE, or IN() operators:

这是范围查询。

explain的type_第4张图片
除了typerange以外,key告诉了你索引类型, key_len是索引长度,refrange的类型下为null

  • index

The index join type is the same as ALL, except that the index tree is scanned.

index全索引扫描,性能倒数第二差。

但好歹还是用了索引。

explain的type_第5张图片

  • all

A full table scan is done for each combination of rows from the previous tables. This is normally not good if the table is the first table not marked const, and usually very bad in all other cases. Normally, you can avoid ALL by adding indexes that enable row retrieval from the table based on constant values or column values from earlier tables.

全表扫描。不能写这样的sql。

explain的type_第6张图片

你可能感兴趣的:(MySQL)