程序员面试宝典之数据库的一个问题?查数据表中第30到第40条记录,有字段ID,但ID不连续

解法一:

  select top 10* from test  where id  not in (select top 29 id from test) 

例如,我有以下这个test表:

当我选取第六行到第十行的数据时,

 select top 5* from test  where id  not in (select top 5 id from test) 

解法二:

//先创建一个临时表,其中testid除了设置成int类型外,还设置成 identity(1,1)类型

他可以实现自定增长,第一个参数是初始值,第二个是增长量

create table #test1(

 testid int identity(1,1),

 id int primary key ,

 name varchar(25))

//效果


//把test表中的数据插入临时表

 insert #test1(id,name)

 select id,name from test 

//把表test和临时表进行内连接

 select a.id,a.name from #test1 a

 inner join test on a.id=test.ID

 and testid >5 and testid<10

//结果

解法三:

可用 ROW_NUMBER 这个内置的函数来解决,它适用于SQL Server2005及以上的版本。

select *from(

 select id,ROW_NUMBER() over (order by id asc) as rowid

  from test)T where T.rowid>5 and rowid<=10

                                            

其中,over (order by id asc)是必需的,它相当于把我们的表test用1,2,3,4.....来标记每一行,而这个行号就是rowid

猜你喜欢

转载自blog.csdn.net/qq_20406597/article/details/81135482
今日推荐