且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不能在 WHERE 子句中使用别名,但可以在 ORDER BY 中使用

更新时间:2023-02-04 23:18:47

出现这种情况是因为查询处理顺序很自然,如下:

This happens because of natural query processing order, which is the following:

  1. FROM
  2. 开启
  3. 外层
  4. WHERE
  5. GROUP BY
  6. CUBE |ROLLUP
  7. 拥有
  8. SELECT
  9. DISTINCT
  10. ORDER BY
  11. TOP

您正在 SELECT 语句中指定别名.正如你所看到的,WHERESELECT 之前被处理,而 ORDER BY 在它之后.这就是原因.现在有什么解决方法:

You're assigning your alias in SELECT statement. As you can see WHERE is processed before SELECT and ORDER BY comes after it. That's the reason. Now what are the workarounds:

  • 子查询.但它们可能难以阅读.
  • 交叉申请.这应该美化您的代码,并且是推荐的方法.
  • Subqueries. But they can be hard to read.
  • CROSS APPLY. This should beautify your code a bit and is recommended method.

CROSS APPLY 将在 WHERE 语句之前分配别名,使其在其中可用.

CROSS APPLY will assign alias before WHERE statement, making it usable in it.

SELECT [Hotel Id]
    , latitude
    , longitude
    , establishmentname
    , Distance
FROM [dbo].[RPT_hotels]
CROSS APPLY (
    SELECT 6371 * ACos(Cos(RADIANS(Latitude)) * Cos(RADIANS('50.017466977673905')) * Cos(RADIANS('24.69924272460935') - RADIANS(Longitude)) + Sin(RADIANS(Latitude)) * Sin(RADIANS('50.017466977673905')))
    ) AS T(Distance)
WHERE distance < 30
ORDER BY Distance;

如果你想了解更多.请阅读这个问题:执行顺序是什么这个SQL语句

If you want to find out more. Please read this question: What is the order of execution for this SQL statement