原因别名在 ORDER BY 中有效,但在 WHERE 中无效 [重复]
Posted
技术标签:
【中文标题】原因别名在 ORDER BY 中有效,但在 WHERE 中无效 [重复]【英文标题】:Reason alias works in ORDER BY but not in WHERE [duplicate] 【发布时间】:2018-01-31 13:28:48 【问题描述】:我知道I can't reference an alias in the WHERE clause,但这是为什么呢?是不是有不同的解释?
这样的事情会产生错误:
declare @myTable table
(
num numeric(5,2),
den numeric(5,2)
)
insert into @mytable
select 1, 2
union
select 1, 3
union
select 2, 3
union
select 2, 4
union
select 2, 5
union
select null, 1
select num/den as 'calc' from @myTable
where calc is not null
order by calc
但这会返回行:
declare @myTable table
(
num numeric(5,2),
den numeric(5,2)
)
insert into @mytable
select 1, 2
union
select 1, 3
union
select 2, 3
union
select 2, 4
union
select 2, 5
union
select null, 1
select num/den as 'calc' from @myTable
--where calc is not null
order by calc
【问题讨论】:
没关系,找到原因了:***.com/questions/31808423/… 【参考方案1】:正如Cannot use Alias name in WHERE clause but can in ORDER BY中提到的,这是由于自然查询处理顺序:
FROM
ON
OUTER
WHERE
GROUP BY
CUBE
| ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP
【讨论】:
以上是关于原因别名在 ORDER BY 中有效,但在 WHERE 中无效 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
SQL 查询 MATCH 与别名和 order by 并优化查询
SQL语句中,为啥where子句不能使用列别名,而order by却可以?