MySQL LIMIT 是在 ORDER BY 之前还是之后应用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4974639/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:43:47  来源:igfitidea点击:

Is MySQL LIMIT applied before or after ORDER BY?

sqlmysqlsql-order-bylimit

提问by Chris Abrams

Which one comes first when MySQL processes the query?

当 MySQL 处理查询时,哪个先出现?

An example:

一个例子:

SELECT pageRegions
FROM pageRegions WHERE(pageID=?) AND(published=true) AND (publishedOn<=?)
ORDER BY publishedON DESC
LIMIT 1';

Will that return the last published pageRegion even if the record does not match the revision datetime IF LIMIT is applied after ORDER BY?

如果在 ORDER BY 之后应用 LIMIT,即使记录与修订日期时间不匹配,这是否会返回最后发布的 pageRegion?

采纳答案by Marc B

Yes, it's after the ORDER BY. For your query, you'd get the record with the highest publishedOn, since you're ordering DESC, making the largest value first in the result set, of which you pick out the first one.

是的,它在 ORDER BY 之后。对于您的查询,您将获得最高的publishOn 记录,因为您正在订购DESC,在结果集中首先制作最大值,您从中挑选出第一个。

回答by RichardTheKiwi

The limitis always applied at the end of result gathering, therefore after order by.

所述limit总是被施加在结果集的结尾,因此之后order by

Given all your clauses, the order of processing will be

鉴于您的所有条款,处理顺序将是

  • FROM
  • WHERE
  • SELECT
  • ORDER BY
  • LIMIT
  • 在哪里
  • 选择
  • 订购者
  • 限制

So you will get the closest record <= publishedOn matching all the conditions in the WHERE clause.

因此,您将获得与 WHERE 子句中的所有条件匹配的最接近的记录 <=publishedOn。

回答by Cristian

Just wanted to point out the in case of MySQL ordering is applied before limiting the results. But this is not true for other DB.

只是想指出在限制结果之前应用 MySQL 排序的情况。但这对于其他 DB 而言并非如此。

For example Oracle first limits results and applies ordering on said results. It makes sense when you think about it from a performance point of view. In MySQL you are actually ordering the entire DB(> 1000 records) to get 2

例如,Oracle 首先限制结果并对所述结果应用排序。当您从性能的角度考虑时,这是有道理的。在 MySQL 中,您实际上是在订购整个 DB(> 1000 条记录)以获得 2