T-SQL聚合函数max+子查询引发的灵异事件

select top 2 Id from Account

引用内容 引用内容
Id
-----------
1
2

(2 行受影响)

select top 2 Id from Account order by Id desc

引用内容 引用内容
Id
-----------
5
4

(2 行受影响)

select * from (select top 2 Id from Account) as tab

引用内容 引用内容
Id
-----------
1
2

(2 行受影响)

select max(Id) Id from (select top 2 Id from Account) as tab

引用内容 引用内容
Id
-----------
5

(1 行受影响)

第4句sql结果本应是2,但执行结果却是Account表最大Id的值5,SQL Server2000/2008上测试都是这个结果,真是鬼诡!

------------------------------------------------------------------

CSDN网友josy回复子查询不指定排序规则,查询结果顺序是不确定的,下边语句可以得到预期的结果:
select max(Id) Id from (select top 2 Id from Account order by id) as tab


评论: 0 | 引用: 0 | 查看次数: 2742
发表评论
登录后再发表评论!