木子屋 Dnawo's BLOG

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

👤 dnawo 📅 2013-06-20 👁 3488 👍 0 💬 0 🔄 来源:本站原创
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)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 SQL Server数据误删恢复方法 下一篇 → Windows任务管理器截图一二三