[英]MySQL EXPLAIN showing ALL type although INDEX exists
I ran the below query using EXPLAIN
我使用
EXPLAIN
运行以下查询
EXPLAIN SELECT form.id AS `Reference No.`,
department.name AS `Department`,
section.name AS `Section`
FROM form
JOIN department
ON form.deptid = department.id
JOIN section
ON form.sectid = section.id
Does type ALL
in the first row indicate that there is going to be performance issues? 第一行中键入
ALL
是否表示会出现性能问题?
+----+-------------+------------+--------+---------------+---------+---------+----------------------+------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows |
+----+-------------+------------+--------+---------------+---------+---------+----------------------+------+
| 1 | SIMPLE | form | ALL | deptid,sectid | | | | 779 |
| 1 | SIMPLE | department | eq_ref | PRIMARY | PRIMARY | 4 | wfs-test.form.deptid | 1 |
| 1 | SIMPLE | section | eq_ref | PRIMARY | PRIMARY | 4 | wfs-test.form.sectid | 1 |
+----+-------------+------------+--------+---------------+---------+---------+----------------------+------+
There is no reason for MySQL to use the index when it gets data from table form
. 当MySQL从表
form
获取数据时,没有理由使用索引。 Because the query doesn't have any WHERE
clause, potentially all the rows from table from
will be included in the final result set. 由于查询没有任何
WHERE
子句,因此表from
所有行都可能包含在最终结果集中。 More, because there is no ORDER BY
clause, any order of the rows is good enough. 而且,因为没有
ORDER BY
子句,所以行的任何顺序都足够好。 This is why MySQL gets the rows directly from the table, without consulting any index. 这就是为什么MySQL直接从表中获取行而不查询任何索引的原因。
Adding a WHERE
condition could trigger the use of an index if an index that contains (some of) the fields involved in the WHERE
conditions exist (and the fields, put in the correct order, are the leftmost columns included in the index). 如果存在包含
WHERE
条件中涉及的字段(某些)的索引(并且字段以正确的顺序排列,则是索引中最左边的列),则添加WHERE
条件可能会触发索引的使用。
Adding an ORDER BY
clause (without WHERE
) on fields from table form
could also trigger the use of an index when all the fields selected from table form
are contained in the index. 添加
ORDER BY
子句(没有WHERE
从表中的字段) form
也可以触发使用索引当从表中选择的所有字段form
被包含在索引中。 It will change the type from ALL
to index
which means it will do a full scan of the index instead of the data rows to get the data it needs. 它将类型从
ALL
更改为index
,这意味着它将对索引(而不是数据行)进行完整扫描以获取所需的数据。 While this is still a full scan, a full index scan
usually runs faster than a full table scan
because less data is loaded from the storage and parsed (the index is usually smaller than the table data). 尽管这仍然是全盘扫描,但由于从存储中加载和解析的数据较少(索引通常小于表数据),因此
full index scan
通常比full table scan
运行得更快。
More information about this can be found in the MySQL documentation . 有关此信息的更多信息,请参见MySQL文档 。
The entire section "8.2.1 Optimizing SELECT Statements" is worth reading to better understand how to write faster queries. 整个章节“ 8.2.1优化SELECT语句”值得一读,以更好地了解如何编写更快的查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.