8.2.1.18 DISTINCT Optimization优化

DISTINCT combined with ORDER BY needs a temporary table in many cases.在许多情况下,DISTINCTORDER BY相结合需要一个临时表。

Because DISTINCT may use GROUP BY, learn how MySQL works with columns in ORDER BY or HAVING clauses that are not part of the selected columns. 因为DISTINCT可能会使用GROUP BY,所以请了解MySQL如何按ORDER BY处理列,或者如何使用不属于所选列的子句。See Section 12.20.3, “MySQL Handling of GROUP BY”.请参阅第12.20.3节,“分组的MySQL处理”

In most cases, a DISTINCT clause can be considered as a special case of GROUP BY. 在大多数情况下,DISTINCT子句可以被视为GROUP BY的特例。For example, the following two queries are equivalent:例如,以下两个查询是等效的:

SELECT DISTINCT c1, c2, c3 FROM t1
WHERE c1 > const;

SELECT c1, c2, c3 FROM t1
WHERE c1 > const GROUP BY c1, c2, c3;

Due to this equivalence, the optimizations applicable to GROUP BY queries can be also applied to queries with a DISTINCT clause. 由于这种等价性,适用于GROUP BY查询的优化也可以应用于具有DISTINCT子句的查询。Thus, for more details on the optimization possibilities for DISTINCT queries, see Section 8.2.1.17, “GROUP BY Optimization”.因此,有关DISTINCT查询的优化可能性的更多详细信息,请参阅第8.2.1.17节,“GROUP BY优化”

When combining LIMIT row_count with DISTINCT, MySQL stops as soon as it finds row_count unique rows.当将LIMIT row_countDISTINCT相结合时,MySQL会在发现行数唯一的行时立即停止。

If you do not use columns from all tables named in a query, MySQL stops scanning any unused tables as soon as it finds the first match. 如果不使用查询中命名的所有表中的列,MySQL会在找到第一个匹配项后立即停止扫描任何未使用的表。In the following case, assuming that t1 is used before t2 (which you can check with EXPLAIN), MySQL stops reading from t2 (for any particular row in t1) when it finds the first row in t2:在以下情况下,假设t1t2之前使用(您可以使用EXPLAIN进行检查),MySQL在找到t2中的第一行时停止从t2读取(对于t1中的任何特定行):

SELECT DISTINCT t1.a FROM t1, t2 where t1.a=t2.a;