1

我创建了一个包含 100k 行的测试表。此查询的执行时间:

SELECT id FROM table

0.032s。如果我GROUP BY为索引为 的整数列添加语句,Normal,BTREE则查询的执行时间:

SELECT id FROM table GROUP BY indexedColumn

解释输出:

id | select_type | table | type |    possible keys   | key  | key_len | ref |  rows  | Extra
 1      SIMPLE    [table]  All    [indexedColumnKey]   null    null    null   105416   Using temporary; Using filesort

0.073s。由于 ,执行时间加倍GROUP BY,但我假设这是正常的?我的问题是为什么要添加LIMIT到查询中,如下所示:

SELECT id FROM table GROUP BY indexedColumn LIMIT 500

解释输出:

id | select_type | table | type |      possible keys    |        key        | key_len | ref |  rows  | Extra
 1      SIMPLE    [table]  index    [indexedColumnKey]   [indexedColumnKey]      5      null   500     null

将执行时间增加到0.301s? 这是超过 4 倍的减速。

我对 SQL 非常缺乏经验,所以这可能是完全正常的,但对我来说,限制返回的行数会大大降低查询速度,这似乎违反直觉。

问题:

  1. 这是正常的吗?
  2. 有什么办法可以阻止 LIMIT 减慢查询速度?
4

1 回答 1

0

该查询SELECT id FROM table GROUP BY indexedColumn不使用索引。它显示在您的解释中。但是当您使用限制时,将使用索引。此外,对于实验,您可以使用 SQL_NO_CACHE 禁用缓存SELECT SQL_NO_CACHE ....

于 2014-02-03T12:42:55.637 回答