SQL 分页查询的两种思路

------分页查询-------
------要分页显示,首先确定一个排序方式。否则分页没有意义
------分页显示7条数据-----
—sql 2000

-----第一页

select top 7 * from  table order by col asc

----查询出前两页的

select top(7*2) from table order by col asc 

----第二页,思路

select top 7 * from table where col not in 
(select top (7*(2-1)) col from table order by col asc)
order by col asc

----第五页

select top 7 * from table where col not in 
(select top (7*(5-1)) col from table order by col asc)
order by col asc

—sql 2005--------使用row_Number()实现分页
—1.为数据排序,然后编号

select *,rN=row_number() over(order by col asc) from table 

–2.根据用户要查看的煤业记录条数,以及要查看的第几页,确定应该查询第几条到第几条
–每页显示7条,要查看第8页
–rN (8-1)7+1…87

select *
from  (select *,rN=row_number() over(order by col asc) from table) as t
where t.rN between (8-1)*7+1 and 8*7

演示案例
使用北风数据库

select * from Orders
--每页显示10个订单,显示第12页订单
select *,rN=ROW_NUMBER() over (order by OrderId asc) from Orders

select * from 
(select *,rN=ROW_NUMBER() over (order by OrderId asc) from Orders) as t
where t.rN between (12-1)*10+1 and 12*10
发布了55 篇原创文章 · 获赞 4 · 访问量 1425

猜你喜欢

转载自blog.csdn.net/BowenXu11/article/details/104727996