在许多情况下,DISTINCT
combined with ORDER BY
needs a temporary table in many cases.DISTINCT
与ORDER 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
with row_count
DISTINCT
, MySQL stops as soon as it finds row_count
unique rows.LIMIT
与row_count
DISTINCT
相结合时,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
:t1
在t2
之前使用(您可以使用EXPLAIN
进行检查),MySQL在找到t2
中的第一行时停止从t2
读取(对于t1
中的任何特定行):
SELECT DISTINCT t1.a FROM t1, t2 where t1.a=t2.a;