数据库分页技术能够帮助浏览者更好的查看信息,不同数据库实现分页时的方法也各有不同。本文主要介绍几种不同数据库分页显示的实现方法以及高效率分页技术的三个方案。
不同数据库分页技术的实现代码:
1.Oracle:select * from ( select query.*, rownum rn from (
query_SQL ) query where rn =< max) where rn >= min
2.SQL Server:select top @pagesize * from tablename where id
not in (select top @pagesize*(@page-1) id from tablename order by id) order by
id
3.MySQL:select * from tablename limit position, counter
(注意:position从0开始,counter表示要获取的记录条数)
或者 select * from tablename limit counter (等同于select * from
tablename limit 0, counter )
4.DB2:select * from (select *,rownumber() as rn from
tablename) where rn between min and max
高效率的分页技术三方案:
1.分页方案一:(利用Not In和SELECT TOP分页)效率次之
语句形式:
SELECT TOP 页大小 * FROM TABLENAME
WHERE
( ID NOT IN (SELECT TOP 每页大小*(待查询页数-1)
ID FROM TABLENAME ORDER BY ID ) )
ORDER BY ID
例如查询21-30
SELECT TOP 10 * FROM TABLENAME
WHERE ( ID NOT IN ( SELECT TOP 20 ID FROM
TABLENAME ORDER BY ID) )
ORDER BY ID
思路:先查询出待查询页之前的全部条数的id,查询ID不在这些ID中的指定数量条数。
2.分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高
语句形式:
SELECT TOP 页大小 * FROM TABLENAME
WHERE ( ID > (
SELECT MAX(id) FROM( SELECT TOP 每页大小*(待查询页数-1) id FROM
TABLENAME ORDER BY id ) AS T) ) ORDER
BY ID
例如查询21-30
SELECT TOP 10 * FROM
TABLENAME WHERE( ID > (
SELECT MAX(id) FROM ( SELECT TOP 20 id FROM
TABLENAME ORDER BY id ) AS T ) ) ORDER BY ID
思路:先获得待查询页的之前全部条数id,获得它们当中最大的ID号,以此最大ID号为标志,查找比这个ID号大的指定条数。
3.分页方案三:
SELECT TOP 每页条数 * FROM (SELECT TOP 待查询页*每页条数
* from TABLENAME order by id)
order by id desc
思路:先正排序查询出待查询页之前(包括当前页)的全部条数,然后将其倒排序,取指定条数。