一、DB2:
DB2分页查询
SELECT * FROM (Select 字段1,字段2,字段3,rownumber() over(ORDER BY 排序用的列名 ASC) AS rn from 表名) AS a1 WHERE a1.rn BETWEEN 10 AND 20
以上表示提取第10到20的纪录
select * from (select rownumber() over(order by id asc ) as rowid from table where rowid startIndex
如果Order By 的字段有重复的值,那一定要把此字段放到 over()中
select * from ( select ROW_NUMBER() OVER(ORDER BY DOC_UUID DESC) AS ROWNUM, DOC_UUID, DOC_DISPATCHORG, DOC_SIGNER, DOC_TITLE from DT_DOCUMENT ) a where ROWNUM > 20 and ROWNUM <=30
增加行号,不排序
select * from ( select ROW_NUMBER() OVER() AS ROWNUM,t.* from DT_DOCUMENT t ) a
增加行号,按某列排序
select * from ( select ROW_NUMBER() OVER( ORDER BY DOC_UUID DESC ) AS ROWNUM,t.* from DT_DOCUMENT t ) a
二、Mysql:
最简单
select * from table limit start,pageNum
比如从10取20个数据
select * from table limit 10,20
三、Oracle:
select * from (select rownum,name from table where rownum startIndex
例如从表Sys_option(主键为sys_id)中从第10条记录开始检索20条记录,语句如下:
SELECT * FROM (SELECT ROWNUM R,t1.* From Sys_option where rownum = 10
四、 sql server:
分页方案一:(利用Not In和SELECT TOP分页)
语句形式:
SELECT TOP 10 *FROM TestTableWHERE (ID NOT IN(SELECT TOP 20 idFROM TestTableORDER BY id))ORDER BY IDSELECT TOP 页大小 *FROM TestTableWHERE (ID NOT IN(SELECT TOP 页大小*页数 idFROM 表ORDER BY id))ORDER BY ID
————————————-
分页方案二:(利用ID大于多少和SELECT TOP分页)
语句形式:
SELECT TOP 10 *FROM TestTableWHERE (ID >(SELECT MAX(id)FROM (SELECT TOP 20 idFROM TestTableORDER BY id) AS T))ORDER BY IDSELECT TOP 页大小 *FROM TestTableWHERE (ID >(SELECT MAX(id)FROM (SELECT TOP 页大小*页数 idFROM 表ORDER BY id) AS T))ORDER BY ID
————————————-
分页方案三:(利用SQL的游标存储过程分页)
create procedure XiaoZhengGe@sqlstr nvarchar(4000), --查询字符串@currentpage int, --第N页@pagesize int --每页行数asset nocount ondeclare @P1 int, --P1是游标的id@rowcount intexec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount outputselect ceiling(1.0*@rowcount/@pagesize) as 总页数--,@rowcount as 总行数,@currentpage as 当前页set @currentpage=(@currentpage-1)*@pagesize+1exec sp_cursorfetch @P1,16,@currentpage,@pagesizeexec sp_cursorclose @P1set nocount off
其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。
通过SQL 查询分析器,显示比较:我的结论是:
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not In和SELECT TOP分页) 效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用