手寫分頁sql 請說說sql高效分頁??

2021-10-13 08:41:38 字數 1354 閱讀 9505

網上已經有很多演算法了,我一直用顛顛倒倒法,是拼接sql的,相容多種資料庫,不喜歡用儲存過程。

公式:select [顯示的字段] from [表名|檢視名] where [主鍵字段] in

( select top pagesize [主鍵字段] from

(select top [主鍵字段] , [排序字段] from     --有幾個排序欄位就寫幾個字段

[表名|檢視名] [ where 查詢條件 ]

order by

[排序欄位1] asc|desc ,[排序欄位2] desc|asc,[主鍵字段] asc|desc

) as aa

order by

[排序欄位1] desc|asc,        --如果上面是倒序,那麼這裡就是正序

[排序欄位2] asc|desc,[主鍵字段] desc|asc

order by

[排序欄位1] asc|desc,    --如果上面是倒序,那麼這裡就是正序,所謂顛顛倒倒。

[排序欄位2] desc|asc,[主鍵字段] asc|desc

說明:products表為例,一頁顯示10條資料,categoryid = 3 為查詢條件,按照unitprice倒序,由於unitprice 字段可能有重複值,所以加上乙個排序字段——productid ,即按照 unitprice desc,productid來排序。 顯示第二頁的資料,sql語句:

select * from products where productid in

(select top 10 productid from

(select top 20 productid , unitprice from products where categoryid = 3 order by unitprice desc,productid ) as aa

order by unitprice asc, productid desc)

order by unitprice desc, productid

這裡查詢條件加一次就可以。

第三個select 語句,要取從第一條資料到要顯示的頁的資料,越是後面的記錄top n就會越大,提取的資料只寫排序需要的字段(主鍵欄位和排序字段)。

第二個select 語句是去掉前面不需要的頁裡的資料,只保留要顯示的頁號裡的資料。

第乙個select 語句,用主鍵字段 in () 的方式提取其他需要的字段。

這種分頁演算法有乙個小的bug,就是顯示最後一頁資料的時候,會多出來幾條記錄,不過這個bug已經在分頁控制項裡面修正了,最後一頁的分頁演算法,採用特殊的select語句。

就是要求表必須有主鍵,而不能是聯合主鍵,引為要用 in 的方式查詢資料。但是並沒有要求主鍵自身必須能夠排序。

手寫分頁sql 分頁查詢SQL語句

表結構 drop table if exists zhoufoxcn userlist create table zhoufoxcn userlist userid int 10 unsigned not null auto increment,username varchar 45 not nul...

oracle 排序分頁 高效sql語句

最好還是利用分析函式row number over partition by col1 order by col2 比如想取出100 150條記錄,按照tname排序 select tname,tabtype from select tname,tabtype,row number over ord...

SQL2005 高效分頁sql查詢語句經典例項

方法一 sql2005 高效分頁sql查詢語句經典例項 如下 select top 10 from select top page 10 row number over order by id as rownum,id,username from guest where username user ...