oracle不支持mysql的limit功能,推荐使用fetch

一、MYSQL使用limit返回指定的行数

select * from table limit m,n;  //从m+1行开始返回,返回n行
select * from table limit n;  //相当于select * from table limit 0,n;
select * from table limie m,-1;  //从m+1行开始返回,返回至最后一行

1、从http://www.xuesql.cn/得到测试数据

 

b、select * from table limit m,n; 从m+1行开始返回,共返回n行

SELECT * FROM movies limit 5,5;

c、select * from table limit n;

SELECT * FROM movies limit 5;

 

d、select * from table m,-1;

SELECT * FROM movies limit 5,-1;

 

 二、oracle使用rownum来返回指定的行数(rownum不是用户自定义的字段,是系统定义的伪列)或者offset/fetch新特性

select first_name,last_name,hire_date from employees;  //共107行数据

employees表创建参考连接:https://www.cnblogs.com/muhai/p/16169598.html

1、rownum的使用(从1开始),比较复杂,推荐使用fetch

(1)、从头查询方式,不支持从中间查询

select employee_id,first_name,last_name,salary from employees where rownum<5;  //返回前4行
select employee_id,first_name,last_name,salary from employees where rownum>5;  //返回空,因为不支持>符号
select employee_id,first_name,last_name,salary from employees where rownum=1;  //返回1行,如果m=1,返回第一行;m≠1就返回空

(2)、从中间查询方式,通过子查询返回第2行到第5行数据

select * from (select employee_id,first_name,last_name,salary,rownum as num from employees) where num between 2 and 5;  //将rownum伪列变成物理列,再通过子查询查出来,

(3)、从中间查询方式,通过交集相减查询返回第2行到第5行

select employee_id,first_name,last_name,salary from employees where rownum<6 minus select employee_id,first_name,last_name,salary from employees where rownum<2;

2、不通过子查询或交集减返回中间的行数,直接通过fetch和offset,offset n是从头跳过n行,fetch first|next m是取前m行或接下来的m行,50 percent是取50%的数据,如果后面跟only,一半后的数据和前面相同也不会输出;如果后面跟with ties,那一半后的数据和前面相同的就会输出

select employee_id,first_name,last_name,salary from employees order by 1 fetch first 5 rows only;  //取前5行,order by在fetch前面
select employee_id,first_name,last_name,salary from employees order by 1 offset 5 row fetch next 5 rows only;  //跳过前面5行,取下面的5行
select employee_id,first_name,last_name,salary from employees order by 1 fetch first 50 percent rows only; 
select employee_id,first_name,last_name,salary from employees order by 1 fetch first 50 percent rows with ties;  

详细知识讲解参考https://blog.csdn.net/mitedu/article/details/3584399

 

posted @ 2021-11-01 21:45  微风徐徐$  阅读(1136)  评论(0编辑  收藏  举报