常见数据库分页SQL语句

来源:互联网 发布:电气成套报价软件 编辑:程序博客网 时间:2024/06/11 05:46

SQL Server 
        从数据库表中的第M条记录开始取N条记录,利用Top关键字:注意如果Select语句中既有top,又有order by,则是从排序好的结果集中选择:
        SELECT *
        FROM  ( SELECT Top N *  
                         FROM  (SELECT Top (M + N - 1) * FROM 表名称 Order by 主键 desc) t1 ) t2
        Order by 主键 asc

        例如从表Sys_option(主键为sys_id)中从10条记录还是检索20条记录,语句如下:
        SELECT * 
        FROM ( SELECT TOP 20 *
                        FROM (SELECT TOP 29 * FROM Sys_option order by sys_id desc) t1) t2
        Order by sys_id asc
       

 

        select * from (select top 20 * from (select top 29 * from m_info_jg)t1)t2 order by id asc

 


        Oralce数据库
        
从数据库表中第M条记录开始检索N条记录
        SELECT * 
        FROM (SELECT ROWNUM r,t1.* From 表名称 t1 where rownum < M + N) t2
        where t2.r >= M
        例如从表Sys_option(主键为sys_id)中从10条记录还是检索20条记录,语句如下:
        SELECT * 
        FROM (SELECT ROWNUM R,t1.* From Sys_option where rownum < 30 ) t2
         Where t2.R >= 10

 

       minus差分页 select * from table where rownum<=10 minus select * from table where rownum<=5

       rownum伪列select * from (select rownum tid,t.* from table t where rownum<=10) where tid<=10 and tid>=5

       notin相反select * from table where id not in(select id from table where rownum<=5) and rownum<=5

       前题是id排序的select * from table where id>(select max(id) from table where rownum<=5) and rownum<=5



        My sql数据库
        My sql数据库最简单,是利用mysql的LIMIT函数,LIMIT [offset,] rows从数据库表中M条记录开始检索N条记录的语句为:
        SELECT * FROM 表名称 LIMIT M,N

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