各种数据库分页查询SQL

一、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

  以上表示提取第1020的纪录

  select *from (select rownumber() over(order by id asc ) as rowid from table where rowid<=endIndex ) 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.*  fromDT_DOCUMENT  t ) a

增加行号,按某列排序

select * from ( select ROW_NUMBER() OVER( ORDER BY DOC_UUID DESC ) ASROWNUM,t.*  from DT_DOCUMENT  t ) a

二、Mysql:

  最简单

  select *from table limit start,pageNum

  比如从1020个数据

  select *from table limit 10,20

  三、Oracle

  select *from (select rownum,name from table where rownum <=endIndex ) where rownum> startIndex

  例如从表Sys_option(主键为sys_id)中从10条记录还是检索20条记录,语句如下:

  SELECT *

  FROM (SELECTROWNUM R,t1.* From Sys_option where rownum < 30 ) t2

  Where t2.R>= 10

四、 sqlserver:

分页方案一:(利用Not InSELECT TOP分页)
语句形式:
SELECT TOP 10 *
FROM TestTable
WHERE (ID NOT IN
(SELECT TOP 20 id
FROM TestTable
ORDER BY id))
ORDER BY ID


SELECT TOP
页大小 *
FROM TestTable
WHERE (ID NOT IN
(SELECT TOP
页大小*页数 id
FROM

ORDER BY id))
ORDER BY ID

-------------------------------------

分页方案二:(利用ID大于多少和SELECT TOP分页)
语句形式:
SELECT TOP 10 *
FROM TestTable
WHERE (ID >
(SELECT MAX(id)
FROM (SELECT TOP 20 id
FROM TestTable
ORDER BY id) AS T))
ORDER BY ID


SELECT TOP
页大小 *
FROM TestTable
WHERE (ID >
(SELECT MAX(id)
FROM (SELECT TOP
页大小*页数 id
FROM

ORDER BY id) AS T))
ORDER BY ID


-------------------------------------

分页方案三:(利用SQL的游标存储过程分页)
create procedure XiaoZhengGe
@sqlstr nvarchar(4000), --
查询字符串
@currentpage int, --
N
@pagesize int --
每页行数
as
set nocount on
declare @P1 int, --P1
是游标的id
@rowcount int
exec sp_cursoropen @P1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcountoutput
select ceiling(1.0*@rowcount/@pagesize) as
总页数--,@rowcount as 总行数,@currentpage as 当前页
set @currentpage=(@currentpage-1)*@pagesize+1
exec sp_cursorfetch @P1,16,@currentpage,@pagesize
exec sp_cursorclose @P1
set nocount off

其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。

通过SQL 查询分析器,显示比较:我的结论是:
分页方案二:(利用ID大于多少和SELECT TOP分页)效率最高,需要拼接SQL语句
分页方案一:(利用Not InSELECT TOP分页) 效率次之,需要拼接SQL语句
分页方案三:(利用SQL的游标存储过程分页) 效率最差,但是最为通用

你可能感兴趣的:(各种数据库分页查询SQL)