8.2.1.1 WHERE Clause Optimization子句优化

This section discusses optimizations that can be made for processing WHERE clauses. 本节讨论可用于处理WHERE子句的优化。The examples use SELECT statements, but the same optimizations apply for WHERE clauses in DELETE and UPDATE statements.这些示例使用SELECT语句,但DELETEUPDATE语句中的WHERE子句也采用相同的优化。

Note注意

Because work on the MySQL optimizer is ongoing, not all of the optimizations that MySQL performs are documented here.因为MySQL优化器的工作正在进行中,这里并没有记录MySQL执行的所有优化。

You might be tempted to rewrite your queries to make arithmetic operations faster, while sacrificing readability. 您可能会试图重写查询以加快算术运算,同时牺牲可读性。Because MySQL does similar optimizations automatically, you can often avoid this work, and leave the query in a more understandable and maintainable form. 因为MySQL会自动进行类似的优化,所以通常可以避免这项工作,并以更易于理解和维护的形式保留查询。Some of the optimizations performed by MySQL follow:MySQL执行的一些优化如下:

Some examples of queries that are very fast:一些非常快速的查询示例:

SELECT COUNT(*) FROM tbl_name;

SELECT MIN(key_part1),MAX(key_part1) FROM tbl_name;

SELECT MAX(key_part2) FROM tbl_name
  WHERE key_part1=constant;

SELECT ... FROM tbl_name
  ORDER BY key_part1,key_part2,... LIMIT 10;

SELECT ... FROM tbl_name
  ORDER BY key_part1 DESC, key_part2 DESC, ... LIMIT 10;

MySQL resolves the following queries using only the index tree, assuming that the indexed columns are numeric:MySQL仅使用索引树解析以下查询,假设索引列为数字:

SELECT key_part1,key_part2 FROM tbl_name WHERE key_part1=val;

SELECT COUNT(*) FROM tbl_name
  WHERE key_part1=val1 AND key_part2=val2;

SELECT key_part2 FROM tbl_name GROUP BY key_part1;

The following queries use indexing to retrieve the rows in sorted order without a separate sorting pass:以下查询使用索引按排序顺序检索行,无需单独的排序过程:

SELECT ... FROM tbl_name
  ORDER BY key_part1,key_part2,... ;

SELECT ... FROM tbl_name
  ORDER BY key_part1 DESC, key_part2 DESC, ... ;