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一般出現在主鍵索引和唯一索引上。它是至多隻有一條記錄匹配。
按照主鍵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
它也是常用於主鍵索引和唯一性索引。並且只有一條記錄匹配。
我們用=
來展示:
由於後面加了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.
ref
與eq_ref
不同的是,它有多條記錄。
ref
也是一種索引查詢。
我們爲tbl_emp表再插入一條數據:
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:
這是範圍查詢。
除了type
爲range
以外,key
告訴了你索引類型, key_len
是索引長度,ref
在range
的類型下爲null
。
- index
The index join type is the same as ALL, except that the index tree is scanned.
index
全索引掃描,性能倒數第二差。
但好歹還是用了索引。
- 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。