天天看點

Mysql實作分頁

1、Mysql的limit用法

limit分頁公式

(1)limit分頁公式:curPage是目前第幾頁;pageSize是一頁多少條記錄
limit (curPage-1)*pageSize,pageSize
(2)用的地方:sql語句中
select * from student limit(curPage-1)*pageSize,pageSize;      

總頁數公式

(1)總頁數公式:totalRecord是總記錄數;pageSize是一頁分多少條記錄

int totalPageNum = (totalRecord +pageSize - 1) / pageSize;

(2)用的地方:前台UI分頁插件顯示分頁碼

(3)查詢總條數:totalRecord是總記錄數

SELECT COUNT(*) FROM tablename

例如:

select * from orders_history where type=8 limit 100,100;

select * from orders_history where type=8 limit 1000,100;

select * from orders_history where type=8 limit 10000,100;

select * from orders_history where type=8 limit 100000,100;

select * from orders_history where type=8 limit 1000000,100;

但是這種查詢比較慢,因為:limit 200000,200,需要掃描200200行,如果在一個高并發的應用裡,每次查詢需要掃描超過20W行,效率十分低下。

limit m語句

 select * from dept where deptno >10 order by deptno asc limit n;//下一頁

 select * from dept where deptno <60 order by deptno desc limit n//上一頁

這種方式不管翻多少頁隻需要掃描n條資料。

例如:每頁10條資料,目前是第10頁,目前條目ID的最大值是109,最小值是100.(目前100-109)
那麼跳到第9頁:
select * from dept where deptno<100 order by deptno desc limit 0,10;   //倒序

那麼跳到第8頁:
select * from dept where deptno<100 order by deptno desc limit 10,10;

那麼跳到第11頁:
select * from dept where deptno>109 order by deptno asc limit 0,10;