码迷,mamicode.com
首页 > 数据库 > 详细

各种常见数据库分页实现(转)

时间:2015-02-27 15:01:10      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:

 

因为数据量过大,如果一次性查询会耗用大量时间以及性能,因此对数据进行分页显示变得尤为重要,以下就列出一些常用数据库的sql分页实现。 

1.MySQL实现分页 
MySQL实现分页效果比较简单,只有一个limit关键字就可以解决。 

示例:SELECT username,password FROM tb_user WHERE id = 1 LIMIT 100,10; 
具体:select * from tableName where 条件 limit 当前页码*页面容量-1,页面容量 

2.Oralce实现分页 

SELECT * 
  FROM (SELECT A.*, ROWNUM RN FROM (SELECT * FROM tableName order by id) A WHERE ROWNUM <=20) 
WHERE RN >= 11; 

select count(*) from tableName where 条件 


3.Sqlserver实现分页 

sqlserver由于版本的不同,分页的实现方式也各不相同。 

SQL 2000 用临时表解决,通过在临时表中增加自增列解决RowNumber。 
DECLARE @Start INT 
DECLARE @End INT 
SELECT @Start = 14000,@End = 14050 

CREATE TABLE #employees (RowNumber INT IDENTITY(1,1), 
LastName VARCHAR(100),FirstName VARCHAR(100), 
EmailAddress VARCHAR(100)) 

INSERT INTO #employees (LastName, FirstName, EmailAddress) 
SELECT LastName, FirstName, EmailAddress 
FROM Employee 
ORDER BY LastName, FirstName, EmailAddress 
SELECT LastName, FirstName, EmailAddress 
FROM #employees 
WHERE RowNumber > @Start AND RowNumber <= @End 

DROP TABLE #employees 

GO   

SQL 2005/2008 由于支持了Row_Number于是通过派生表的方式解决(两个嵌套) 
DECLARE @Start INT 
DECLARE @End INT 
SELECT @Start = 14000,@End = 14050 

SELECT LastName, FirstName, EmailAddress 
FROM (SELECT LastName, FirstName, EmailAddress, 
ROW_NUMBER() OVER (ORDER BY LastName, FirstName, EmailAddress) AS RowNumber 
FROM Employee) EmployeePage 
WHERE RowNumber > @Start AND RowNumber <= @End 
ORDER BY LastName, FirstName, EmailAddress 
GO 
   

SQL 2005/2008 或者用CTE的方式实现,和派生表一样,就是好看点,执行计划都一样。 
DECLARE @Start INT 
DECLARE @End INT 
SELECT @Start = 14000,@End = 14050; 
WITH EmployeePage AS 
(SELECT LastName, FirstName, EmailAddress, 
ROW_NUMBER() OVER (ORDER BY LastName, FirstName, EmailAddress) AS RowNumber 
FROM Employee) 
SELECT LastName, FirstName, EmailAddress 
FROM EmployeePage 
WHERE RowNumber > @Start AND RowNumber <= @End 
ORDER BY LastName, FirstName, EmailAddress 
GO 
   
SQL SERVER 2012 比较给力支持了OFFSET,于是一个Select结束战斗,另外在2012里,如果前面加上TOP(50),那么执行计划就会少读很多行数据(读的精准了),提高性能。 
SELECT top(50) LastName, FirstName, EmailAddress 
FROM Employee 
ORDER BY LastName, FirstName, EmailAddress 
OFFSET 14000 ROWS 
FETCH NEXT 50 ROWS ONLY; 

4.DB2实现分页 
Db2实现分页与SQL Server类似, 但是可以不对资料排序(起始位置从1开始) 

对资料排序 
select * from ( 
    select t.*, ROW_NUMBER() OVER(ORDER BY CARD_ID asc) AS ROWNUM from CARD t ) a 
where ROWNUM > 20 and ROWNUM <=30 

不对资料排序 
select * from ( 
    select t.*, ROW_NUMBER() OVER() AS ROWNUM from CARD t ) a 
where ROWNUM > 20 and ROWNUM <=30 


以上为各种常见数据库分页语句,留存备用。

http://lafecat.iteye.com/blog/2186265

 

各种常见数据库分页实现(转)

标签:

原文地址:http://www.cnblogs.com/softidea/p/4303161.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!