子查询的问题

starfly578 2010-02-09 11:24:13
select * from test2 t where t.id in (select top 2 id from test2 where point=t.point ) 

用来显示,所有成绩相同的前两条记录,结果没有问题,就是想不明白是怎么实现的。
select top 2 id from test2 where point=t.point

是如何实现查询成绩相同的前两条记录的?
返回的结果,是按id从小到大排列的,并不是成绩相同的项挨在一起。

有高手能讲哈,这个语句是怎么实现查询结果的么,谢谢了!
...全文
39 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
cxmcxm 2010-02-10
  • 打赏
  • 举报
回复
declare @test2 table (id int identity(1,1),point int)
insert into @test2 (point)
select 60
union all select 60
union all select 60
union all select 60
union all select 70
union all select 70
union all select 70
union all select 70
union all select 80
union all select 80
union all select 80
union all select 81
union all select 82
union all select 83
union all select 90
union all select 90
union all select 90
union all select 90
union all select 90
--select * from @test2

select * from @test2 t
where id in (select top 2 id from @test2 where point=t.point order by id)

用以上例子说明
数据库引擎对每一条记录进行扫描,根据where 中的条件进行判断,子查询的结果对不同的分数是不同的
第一条 1,60 子查询结果是1,2 1 in (1,2) 所以被选中
第二条 2,60 子查询结果还是1,2 2 in (1,2) 所以被选中
第三条 3,60 子查询结果还是1,2 3 in (1,2) 条件不成立 所以不会被选中
第四条 4,70 子查询结果是4,5, 4 in (4,5) 所以被选中
......后面的判断道理相同.







starfly578 2010-02-10
  • 打赏
  • 举报
回复
谢谢二楼的,明白了!
百年树人 2010-02-09
  • 打赏
  • 举报
回复
select * from test2 t where t.id in (select top 2 id from test2 where point=t.point )

可以把主查询的表(别名为t)和子查询的表(test2)看成两个集合A和B

A集合的id等于B集合的前两个ID,这两个集合关联的字段是point
这个查询,准确地讲,子查询里应该还有个order by,像这样

select * from test2 t where t.id in (select top 2 id from test2 where point=t.point order by id)
ACMAIN_CHM 2010-02-09
  • 打赏
  • 举报
回复
select * from test2 t where t.id in (select top 2 id from test2 where point=t.point )

对每一条记录 select * from test2 t 系统都会检查一下 t.id in (select top 2 id from test2 where point=t.point )

34,575

社区成员

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

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