select Id as UserId from [User] where UserId<10000
select Id as UserId from [User] order by UserId desc第一条语句执行会出错,提示列名 'UserId' 无效,第二条语句能正常执行。同样的问题在having中也存在:
select Brand,COUNT(*) as total from [User]
group by Brand having total>1000
order by total desc这是为什么呢?这主要是受Select语句的处理顺序的影响,在SQL Server 2008帮助文档说明如下:
Select语句的处理顺序
1.FROM
2.ON
3.JOIN
4.Where
5.GROUP BY
6.WITH CUBE 或 WITH ROLLUP
7.HAVING
8.Select
9.DISTINCT
10.ORDER BY
11.TOP
由于Where在Select前执行,所以执行Where时列别名还不存在,当然无法使用,而ORDER BY在Select后执行,自然可以使用列别名。处理顺序也解释了为什么表别名在任何地方都可以使用,例如:
select * from [User] a where a.Id<10000 order by a.Id desc
评论(0)
暂无评论。