常用分页查询sql
先介绍一个面试题,查询表中第200-300条数据。应用既是分页查询,先通过子查询对数据进行标记,如oracle通过rownum进行标记,再取一个区间的数据。
一,ORACLE
关键字 rownum
规则:
select * from (select a.*,rownum rc from 表名 where rownum<=endrow) a where a.rc>=startrow
或 SELECT *
FROM (SELECT A.*, ROWNUM RN
FROM (SELECT * FROM TABLE_NAME) A
WHERE ROWNUM <= 40)
WHERE RN > 20
其中的SELECT * FROM TABLE_NAME
表示没有进行分页时的sql查询语句,而ROWNUM 和RN 限定了查询数据的范围。
实例:
select * from ( select OL.*, rownum rc from OffsiteOutreachTeam_List OL where rownum <= 48 ) OL where OL.rc >= 9
SELECT * FROM (SELECT A.*, ROWNUM RN FROM (SELECT * FROM OffsiteOutreachTeam_List) A WHERE ROWNUM <= 40) WHERE RN > 20
select * from ( select OL.*, rownum rc from OffsiteOutreachTeam_List OL) where rc >= 9 and rc <= 20
select * from ( select OL.*, rownum rc from OffsiteOutreachTeam_List OL) where rc between 10 and 20
注意:可以通过排序,避免不同页出现重复的数据。
- SELECT * FROM
- 2 (
- 3 SELECT A.*, ROWNUM RN
- 4 FROM (SELECT ID, OWNER, OBJECT_NAME FROM TEST WHERE OWNER IS NOT NULL ORDER BY OWNER, ID) A
- 5 WHERE ROWNUM <= 20
- 6 )
- 7 WHERE RN >= 11;
二,MySQL
关键字:limit
MySQL数据库分页 Select * from 表名 limit startrow,pagesize (Pagesize为每页显示的记录条数)
三,SQL Servel
关键字:top
3.SQL Server 2000数据库分页 Select top pagesize * from 表名 where 列名 not in(select top pagesize*page 列名 from 表名 order by列名) order by列名
4.SQL Server 2005数据库分页 Select * from (select 列名,row_number() over(order by 列名1) as 别名from 表名) as t where t.列名1>=startrow and t.列名1<=endrow