赞
踩
select * from ( select * from people order by id desc ) where rownum = 1
OFFSET n ROWS FETCH NEXT m ROWS ONLY
从第n行开始,往后取m行(注 不包括第n行数据)FETCH NEXT m ROWS ONLY
从头开始往后取m行在之前所说的,在线oracle学习网站中准备好数据如下:
CREATE TABLE people (
id varchar2(10),
name varchar2(10),
sex varchar2(10)
);
INSERT INTO people VALUES ('1', '小明', '男');
INSERT INTO people VALUES ('2', '小红', '女');
INSERT INTO people VALUES ('3', '小黄', '男');
INSERT INTO people VALUES ('4', '小紫', '男');
INSERT INTO people VALUES ('5', '小绿', '男');
INSERT INTO people VALUES ('6', '小白', '男');
INSERT INTO people VALUES ('7', '大强', '男');
INSERT INTO people VALUES ('8', '大青', '男');
这里将id类比时间字段,一般查询根据时间进行倒序:
select * from people
order by id desc
在oracle数据库中,查询出来的数据,可以通过rownum(行数)来指定具体第几行数据,但需要注意以下几点:
倒序查询之后,获取第一行数据:
select * from (
select * from people
order by id desc
)
where rownum = 1
倒序查询之后,获取前4行数据:
select * from (
select * from people
order by id desc
)
where rownum <= 4
如果不使用嵌套select,则会报错语法错误:
fetch方式除了获取前几行数据,还有另一个作用,就是进行分页的时候使用。
fetch使用需要注意如下几点:
OFFSET n ROWS FETCH NEXT m ROWS ONLY
从第n行开始,往后取m行(注 不包括第n行数据)FETCH NEXT m ROWS ONLY
从头开始往后取m行倒序查询之后,获取第一行数据:
select * from people
order by id desc
fetch next 1 rows only
倒序查询之后,获取前4行数据:
select * from people
order by id desc
fetch next 4 rows only
fetch用于分页,从第n行后,取m返回结果集
select * from people
order by id desc
OFFSET n ROWS FETCH NEXT m ROWS ONLY
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。