SQL查询,执行顺序
如果查询同时包含 group by 和 order by 子句,那么 SQL 的执行顺序是什么?这取决于它们在查询中的位置吗???
What will be the sequence of execution followed by SQL if a query has both group by and order by clause. Does it depend on their position in the query???
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
ORDER BY
始终对GROUP BY
执行的分组结果执行,即始终“after”。在标准 SQL 中,您必须在GROUP BY
词法上将ORDER BY
放在GROUP BY
后面(如果两者都存在),以“提醒您”这一事实。ORDER BY
always executes on the results of the grouping performed byGROUP BY
, i.e., always "after". In standard SQL, you must haveORDER BY
lexically afterGROUP BY
, if both are present, to kind of "remind you" of the fact.为了:
in order:
这取决于很多因素,包括您正在使用的 RDMS。了解正在发生的情况的最佳方法是使用允许您查看查询执行计划的查询工具。
It depends on many things including the RDMS you are using. The best way to find out what is going on is to use a query tool that allows you to see the query execution plan.
排序依据通常发生在最后。
如果您使用的是 SQL Server,请启动查询分析器和执行计划 将为您提供查询的良好图形表示。
Order by generally happens last.
If you're using SQL Server, fire up query analyzer and execution plan will give you a nice graphical representation of your query.
任何 SQL 语句都没有强制执行顺序。要求的结果是与“规范”评估获得的结果相匹配。在规范计算中,ORDER BY 最后应用(即使在计算 SELECT 列表表达式之后),但这并不意味着排序会推迟到实际系统上实际执行查询时的那个点。
The sequence of execution is not mandated by any SQL statement. What is mandated is that the result match the result that would be obtained by a "canonical" evaluation. In the canonical evaluation, the ORDER BY is applied last (even after the SELECT list expressions are evaluated), but that doesn't mean sorting is postponed to that point in the actual execution of a query on a real system.
group by 首先执行,然后对分组的结果进行排序。
group by gets executed first and then the results of the group are ordered.
假设我们有一个 SQL 查询:
SQL 查询子句的执行顺序是:
Let's assume we have SQL query:
the order in which sub-clauses of SQL query are executed is:
我还建议对特定的数据库引擎使用查询分析器。下面是 Postgres 中的一个示例,它解释了 ORDER BY 首先执行,然后是 WHERE 过滤器:
因此,如果我将 DESC 更改为 ASC,结果集将包含不同的记录!
I will also suggest using a query analyzer for the specific database engine. The following is an example in Postgres, which explains that ORDER BY is executed first and after that the WHERE filter:
So if I alter DESC to ASC the result set will contain different records!