常用数据库分页查询(Oracle MySQL SQLServer)
数据库分页查询在实际应用中是很常见的,这篇文章就分享一下常用的三种数据库的分页查询。
说明: [table]表示数据库表名,[SID]表示表[table]的主键列,查询第 [n] 到 [m] 条数据。
1.Oracle
select * from(select rownum RN,B.* from BOOKLIST B) where RN between 8 and 10;
2.SQLServer
(1).SQLServer数据库分页查询方法有很多种,下面这一种是最简洁的
select top [m]-[n] * from [table] where [SID] not in (select top [n] [SID] from [table] order by [SID])order by [SID]
此方法是先取出前[n]条的SID(前两页),排除前[n]条数据的SID,然后在剩下的数据里面取出前[m]-[n]条数据。
缺点就是它会遍历表中所有数据两次,数据量大时性能不好。
(2).这种查询比前面那种方法要好,只会遍历一次所有的数据。适用于Sql Server 2000之后的版本(不含)。
select * from (select *,ROW_NUMBER() over(order by [SID]) ROW_ID from [table]) t where t.ROW_ID between 6 and 10
3.MySQL
select * from [table] limit 5; --查询前5行
select * from [table] limit 0,5; --同上,查询前5行
select * from [table] limit 5,10; --返回6-15行
mysql的分页主要用的书limit这个函数。但是当一个查询语句查询的数据量很大时,如select * from [table] limit 10000,1 , 最好不要直接使用limit,而是先获取到offset的id后,再直接使用limit size来获取数据。
如:
select * From [table] Where [SID] >= (select [SID] From [table] Order By [SID] limit 10000,1)
limit 10;
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
https://fcialisj.com/ - cialis generic buy