SQL 高效分頁(百萬條資料),sql分頁
參考資料:SQL分頁語句
第一種方法:效率最高
SELECT TOP 頁大小 * FROM ( SELECT ROW_NUMBER() OVER (ORDER BY id) AS RowNumber,* FROM table1) as A WHERE RowNumber > 頁大小*(頁數-1) --註解:首先利用Row_number()為table1表的每一行添加一個行號,給行號這一列取名'RowNumber' 在over()方法中將'RowNumber'做了升序排列--然後將'RowNumber'列 與table1表的所有列 形成一個表A--重點在where條件。假如當前頁(currentPage)是第2頁,每頁顯示10個資料(pageSzie)。那麼第一頁的資料就是第11-20條--所以為了顯示第二頁的資料,即顯示第11-20條資料,那麼就讓RowNumber大於 10*(2-1) 即:頁大小*(當前頁-1)
將上面的方法寫成預存程序 (表名Location)
if(exists(select* from sys.procedures where name='p_location_paging'))--如果p_location_paging這個預存程序存在drop proc p_location_paging --那麼就刪除這個預存程序gocreate proc p_location_paging(@pageSize int, @currentPage int)--建立預存程序,定義兩個變數'每頁顯示的條數'和'當前頁'asselect top (@pageSize) * from (select ROW_NUMBER() over(order by locid) as rowid ,* from location )as Awhere rowid> (@pageSize)*((@currentPage)-1)
第二種方法:效率次之
SELECT TOP 頁大小 * --如果每頁顯示10條資料,那麼這裡就是查詢10條資料FROM table1WHERE id > --假如當前頁為第三頁,那麼就需要查詢21-30條資料,即:id>20 ( SELECT ISNULL(MAX(id),0) --查詢子查詢中最大的id FROM (SELECT TOP 頁大小*(當前頁-1) id FROM table1 ORDER BY id --因為當前頁是第三頁,每頁顯示十條資料。那麼我將: 頁大小*(當前頁-1),就是擷取到了在"當前頁""前面"的20條資料。所以上面用max(id)查詢最大的id,取到這個20,那麼前面的where 條件的id>20 即取到了第三頁的資料,即取21-30條資料 ) as A )ORDER BY id
將上面的方法寫成預存程序:表名Location
if(exists(select * from sys.procedures where name='p_location_paging'))drop proc p_location_paginggocreate proc p_location_paging(@pageSize int ,@currentPage int)asselect top (@pageSize) * from locationwhere locId>(select ISNULL(MAX(locId),0)from (select top ((@pageSize)*(@currentPage-1))locid from location order by locId) as a)order by locId
第三種方法:效果最差
SELECT TOP 頁大小 *FROM table1WHERE id NOT IN --where條件陳述式限定要查詢的資料不是子查詢裡麵包含的資料。即查詢"子查詢"後面的10條資料。即當前頁的資料 ( --如果當前頁是第二頁,每頁顯示10條資料,那麼這裡就是擷取當前頁前面的所有資料。 SELECT TOP 頁大小*(當前頁-1) id FROM table1 ORDER BY id )ORDER BY id