几乎每个系统都含有查询功能,而查询基本都需要分页。我知道的分页有前端分页、后端分页、数据库分页,这里写的则是数据库分页了。
select *
from (select A.*, rownum rn
from (select t.*,
(select count(1) from table1 t1) as total
from table1 t ) A
where rownum <= #{limit} + #{start})
where rn >= #{start} + 1;
需要传入参数start、limit,start就是开始的记录行数,首页一般为0,limit则就是页面限制显示的记录数目。
如查询的是table1里面的第1至第20条数据,写法如下:select *
from (select A.*, rownum rn
from (select t.*,
(select count(1) from table1 t1) as total
from table1 t ) A
where rownum <= 20 + 0)
where rn >= 0 + 1;
编程菜鸟一枚,若有什么不对的地方,还望大神们指正。
经常一段时间的实践发现,分页查询与记录总数分开两条sql查询更好更快,即换成下面的方式:
首先分页查询记录
select *
from (select A.*, rownum rn
from (select t.*
from table1 t ) A
where rownum <= 20 + 0)
where rn >= 0 + 1;
再获取记录总数
select count(1) total from table1
最近观察到mybatis自动生成的分页语句如下:
with partdata as
(select t.*, rownum as rn
from (select *
from t1) t
where rownum <= 10)
select * from partdata where rn > 0;