mysql - 如何阻止 LIMIT 减慢查询速度?

标签 mysql sql sql-limit

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

SELECT id FROM table

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

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 大大降低查询速度吗?

最佳答案

查询 SELECT id FROM table GROUP BY indexedColumn 不使用索引。它显示在您的解释中。但是当你使用 limit 时,就会使用索引。 此外,对于实验,您可以使用 SQL_NO_CACHE SELECT SQL_NO_CACHE ....

禁用缓存

关于mysql - 如何阻止 LIMIT 减慢查询速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21064486/

相关文章:

mysql - 如何使用 Entity Framework Core 正确运行迁移和播种 docker MySql DB

mysql - 一次将数据插入多个表时,自动增量无法正常工作

sql - 如何限制laravel中每个类别的结果

sql - 如何在列中找到连续的零?

sql - 在 spark sql 中用 LIMIT 描述

java - 如何使用eclipse将数据插入Google Cloud mysql数据库

sql - 检查TEXT列的内容是否为纯数字

MySQL : How can I only display the minimum values if there is more than 1 row with the same value

c# - MySQLConnection 在 Visual Studio 中抛出异常