oracle 分頁查詢優化


在sql優化過程當中,發現分頁查詢的幾種寫法性能差別較大

第一種

SELECT * FROM (
SELECT row_number() OVER(ORDER BY null) as rn, a.*
FROM TABLE_NAME a
WHERE TO_DATE(substr(a.DE, 0, 8), 'YYYY-MM-DD')>=TO_DATE(:1 , 'YYYY-MM-DD')
) A
WHERE A.RN > :24867
AND A.RN <= :24868 ;
第二種
SELECT * FROM
(
SELECT A.*, ROWNUM RN
FROM (SELECT * FROM TABLE_NAME) A
WHERE ROWNUM <= :24867
)
WHERE RN >=:24868

第二種性能更好,建議使用第二種做分頁查詢

 oracle 12c 以后分頁查詢可以使用top-n語句 ,詳見官方文檔 SQL for Analysis and Reporting (oracle.com)

 

--取前10行

select A.object_id,A.object_name from yz.t1 A  fetch first 10 rows only;

--取第二個10行

select A.object_id,A.object_name from yz.t1 A  OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY;

--取第3個10行,后面依次類推

select A.object_id,A.object_name from yz.t1 A  OFFSET 20 ROWS FETCH NEXT 10 ROWS ONLY;

也可以按百分比分頁

select A.object_id,A.object_name from yz.t1 A  FETCH FIRST 0.0005 PERCENT ROWS ONLY;

select A.object_id,A.object_name from yz.t1 A  OFFSET 25 ROWS FETCH FIRST 0.0005 PERCENT ROWS ONLY;

從第26行開始取值

 

WITH TIES

   與最后一行最后一列相同的其他行

SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary
FETCH FIRST 5 PERCENT ROWS ONLY;

EMPLOYEE_ID LAST_NAME SALARY
----------- --------------------- ------
132 Olson 2100
128 Markle 2200
136 Philtanker 2200
127 Landry 2400
135 Gee 2400
119 Colmenares 2500

SELECT employee_id, last_name, salary
FROM employees
ORDER BY salary
FETCH FIRST 5 PERCENT ROWS WITH TIES;

EMPLOYEE_ID LAST_NAME SALARY
----------- --------------------- ------
132 Olson 2100
128 Markle 2200
136 Philtanker 2200
127 Landry 2400
135 Gee 2400
119 Colmenares 2500
131 Marlow 2500
140 Patel 2500
144 Vargas 2500
182 Sullivan 2500
191 Perkins 2500

 


免責聲明!

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



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