SQL中的”ORDER BY”子句中的列在SELECT语句中不存在。

huangapple go评论139阅读模式
英文:

COLUMN IN SQL ORDER BY CLAUSE NOT PRESENT IN SELECT STATEMENT

问题

根据SQL执行顺序,ORDER BY 在SELECT语句之后执行。然而,我们可以使用在SELECT语句中不存在的列来对结果进行排序。这是否与执行顺序相矛盾?在SELECT语句之后使用了一个不存在的列进行排序?期待获得解释。

英文:

As per the SQL order of execution, ORDER BY gets executed at the end, after the select statement. However, we are able to order by the result using a column that is not present in the SELECT statement. Isn't that contradictory to the order of execution? A column that doesn't exist after the SELECT Statement is being used to order by?

Looking to get an explanation

答案1

得分: 1

如果您在ORDER BY中使用未在SELECT中提及的内容,查询规划器基本上会将其作为虚拟列放入SELECT中。这就是为什么按照未在SELECT中选择的表达式(列或公式)进行排序能够工作的原因。

请记住,SQL是一种声明性语言,可能是我们大多数程序员使用的唯一声明性语言。我们告诉SQL我们想要什么,而不是如何获得它。查询规划器需要确定以下两点:

a)我们所要求的是否合法且可能。

b)如何获得它。

我们程序员通过其他编程语言受过过程式思维的训练。我们不会告诉计算机我们想要什么,而是告诉它如何获得它。但这种训练对SQL并不真正有用。(对于优化查询来说是有用的,但优化始于查看由EXPLAIN显示的查询计划。)

英文:

If you ORDER BY something that isn't mentioned in SELECT, the query planner basically puts it into the SELECT as a phantom column. That's why ordering by a non-SELECTed expression (column or formula) works.

Remember, SQL is a declarative language, probably the only declarative language most of we programmers use. We tell SQL what we want, not how to get it. It's up to the query planner to figure out

a) whether what we asked for is well-formed and possible.

b) how to get it.

We programmers are trained, by other languages, to think procedurally. We don't tell the machine what we want, we tell it how to get it.
But that training isn't really useful for SQL. (It is useful for optimizing queries, but optimization starts with looking at the query plan revealed by EXPLAIN.)

huangapple
  • 本文由 发表于 2023年6月8日 07:51:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76427768.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定