程式設計師面試寶典之資料庫的一個問題?查資料表中第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