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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM