排序依据/限制执行 SQL

Order by / limit execution in SQL

网络上已经有很多线程,只是想了解一些让我感到困惑的细微差别!

引用 doc reference

If you combine LIMIT row_count with ORDER BY, MySQL stops sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result. If ordering is done by using an index, this is very fast.

和一个SO thread

It will order first, then get the first 20. A database will also process anything in the WHERE clause before ORDER BY.

从问题中提取相同的查询:

SELECT article
FROM table1
ORDER BY publish_date
LIMIT 20

假设 table 有 2000 行,其中 query 预计 return 20 行,现在,查看 mysql ref ....stops sorting as soon as it has found the first row_count rows.... 让我感到困惑,因为我觉得它有点模棱两可!!

为什么说stops sortinglimit 子句是否应用于已排序的数据 return 通过 order by 子句编辑( 假设其 non-indexed ) 还是我的理解有误 SQL 是先 limiting 然后排序!!??

文档中提到的优化通常仅在 publish_date 列上有索引时才有效。这些值按顺序存储在索引中,因此引擎只需遍历列的索引,获取关联的行,直到获取 20 行。

如果列没有索引,引擎通常需要获取所有行,对它们进行排序,然后return其中的前 20 个。

了解它如何与 WHERE 条件相互作用也很有用。假设查询是:

SELECT article
FROM table1
WHERE last_read_date > '2018-11-01'
ORDER BY publish_date
LIMIT 20

如果 publish_date 被索引而 last_read_date 没有,它将按顺序扫描 publish_date 索引,根据条件测试关联的 last_read_date,并添加 article 如果测试成功则返回结果集。当结果集中有 20 行时它将停止并且 return 它。

如果last_read_date被索引而publish_date没有,它会使用last_read_date索引来查找所有满足条件的行的子集。然后它将使用 publish_date 列对这些行进行排序,return 前 20 行。

如果两列都没有索引,它将进行完整的 table 扫描以测试 last_read_date,对所有符合条件的行进行排序,并 return 前 20 行.

MySQL stops sorting as soon as it has found the first row_count rows of the sorted result, rather than sorting the entire result

这实际上是 mysql 中非常明智的优化。如果您使用限制 return 20 行并且 mysql 知道它已经找到它们,那么 mysql(或您)为什么会关心其余记录的排序方式?没关系,因此 mysql 停止对其余行进行排序。

如果 order by 是在索引列上完成的,那么 mysql 可以很快判断是否找到了前 n 个记录。