sql语句的执行顺序

NEW1981 2007-10-12 11:57:49
select top 10 id from a order by id desc是怎么执行的?

先选出top 10结果集来再对排序还是先对表中记录排序再选出top 10?

表a
id
1
2
3
...

15
select top 10 id from a order by id desc的结果怎么会是
15
14
13
。。。
6

真是莫名其妙了
...全文
116 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxmcxm 2007-10-13
  • 打赏
  • 举报
回复
先排序后再取前10条
pt1314917 2007-10-13
  • 打赏
  • 举报
回复
select top 10 id from a order by id desc

先排序后取前10条。。
Limpire 2007-10-13
  • 打赏
  • 举报
回复
里面的 order by id 不能被注释,注释后会得到15至6数据。
Limpire 2007-10-13
  • 打赏
  • 举报
回复
declare @A table(id int)
insert @A
select 1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9 union all
select 10 union all
select 11 union all
select 12 union all
select 13 union all
select 14 union all
select 15

select * from
(
select top 10 * from @A-- order by id
) as a
order by id desc

/*
id
10
9
8
7
6
5
4
3
2
1
*/
Limpire 2007-10-13
  • 打赏
  • 举报
回复
要得到10至1的数据:

select id from
(
select top 10 id from a order by id
) as a
order by id desc
netmcuser 2007-10-13
  • 打赏
  • 举报
回复
先Order by,再select
elvis_gao 2007-10-13
  • 打赏
  • 举报
回复

select top 10 id from a order by id desc
/*上面是先排序后再取前10条,如果下面是先正序取10,再倒序排序,如果去掉里面的order by id ASC,则也是先排序后再取前10条*/
select * from (select top 10 * from @A order by id ASC) as A order by A.id desc
晓风残月0110 2007-10-13
  • 打赏
  • 举报
回复
在所属select的语句中先执行排序,之后周十佳
Limpire 2007-10-12
  • 打赏
  • 举报
回复
先 order by 再 top 10

34,587

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧