分页查询是项目中必不可少的一部分,难倒是不难,就是这些东西,长时间不用,就忘的一干二净了。今天特此总结一下这两款数据库分页查询的实现过程(只记录效率比较高的)
一.Oracle中的分页查询
1.通用分页查询模板
SELECT * FROM (SELECT x.*, rownum as m FROM ({0}) x) --{0}为嵌套的查询语句或为一张表 WHERE m >= {1} --{1}取值的最小范围 AND m <= {2} --{2}取值的最大范围
查询的原理是,先用一个子查询,将查询得到的数据进行排列,最外层的查询再根据rownum取范围,下面贴一个实例,方便以后查看
SELECT * FROM (SELECT x.*, rownum as r FROM ( select c.* from Cars c join ResCommend r on c.Id=r.ResId where r.Posld=2 and DeadLine>SYSDATE and c.IsPub='是' order by r.Weight desc ) x) WHERE r >= 0 AND r <= 6
二.Sqlserver中的分页查询
1.用row_number() over()进行分页
select * from (select row_number() over(order by Weight desc) as rownumber,* from ({0}) as hello) as newtable --{0}为嵌套的查询语句或为一张表 where rownumber>={1} --{1}取值的最小范围 and rownumber<={2} --取值的最大范围
查询的原理是,先用row_number()将查询到的数据进行排列,最外层的查询再根据rownumber取范围,下面贴一个实例
select * from (select row_number() over(order by Weight desc) as rownumber,* from ( select c.*,r.Weight from Cars c join ResCommend r on c.Id=r.ResId where r.Posld=2 and DeadLine>GETDATE() and c.IsPub='是' ) as hello) as newtable where rownumber>=0 and rownumber<=6