之前一直在学习SQL Server,然而其的分页查询语句也极其的复杂。所以硬着头皮背了下来。今天使用My SQL的时候就一直在报错。
找了半个小时,后来网上发帖才知道原来,My SQL不能使用。所以就把几个数据库SQL语句汇总了一下。希望对大家有帮助
Oracle:
方法一:
SELECT * FROM
(
SELECT A.*, ROWNUM RN
FROM (SELECT * FROM TABLE_NAME) A
WHERE ROWNUM <= 40
)
WHERE RN >= 21;
方法二:
SELECT * FROM
(
SELECT A.*, ROWNUM RN
FROM (SELECT * FROM TABLE_NAME) A
)
WHERE RN between 21 and 40
公认第二种方法效率没有第一种高。原因是第二种要把子查询执行完,而第一种方法子查询执行到Rownum=40后就结束了。
MySQL:
SELECT * FROM TABLE_NAME LIMIT 10, 20
表示从第11条数据开始取20条数据返回,limit后的2个参数含义为:起点和步长,即从那条数据开始,取多少条数据,再如取前20条数据:SELECT * FROM TABLE_NAME LIMIT 0, 20
SQL Server2000:
SELECT TOP @pagesize * FROM TABLE_NAME WHERE id not in (SELECT TOP @pagesize*(@page-1) id FROM TABLE_NAME ORDER BY id) ORDER BY id
SQL Server 2005:
方法一:
SELECT ...
FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY ID asc) AS RowNum, ......
FROM TABLE_NAME
) AS T
WHERE T.RowNum> 10 and T.RowNum<= 20
方法二:
WITH DataList AS
(
SELECT ROW_NUMBER() OVER (ORDER BY O.ID DESC)AS RowNum, ......
FROM .....
WHERE ......
)
SELECT ......
FROM DataList