MySQL分頁查詢offset過大,Sql優化經驗

低性能版

SELECT
*
FROM table
where condition1 = 0
and condition2 = 0
and condition3 = -1
and condition4 = -1
order by id asc
LIMIT 2000 OFFSET 50000

當offset特別大時,這條語句的執行效率會明顯減低,並且效率是隨着offset的增大而下降的。
緣由爲:
MySQL並非跳過offset行,而是取offset+N行,而後返回放棄前offset行,返回N行,當offset特別大,而後單條數據也很大的時候,每次查詢須要獲取的數據就越多,天然就會很慢。性能

優化版本

SELECT
*
FROM table
JOIN
(select id from table
where condition1 = 0
and condition2 = 0
and condition3 = -1
and condition4 = -1
order by id asc
LIMIT 2000 OFFSET 50000)
as tmp using(id)

或者優化

SELECT a.* FROM table a, 
(select id from table
where condition1 = 0
and condition2 = 0
and condition3 = -1
and condition4 = -1
order by id asc
LIMIT 2000 OFFSET 50000) b 
where a.id = b.id

先獲取主鍵列表,再經過主鍵查詢目標數據,即便offset很大,也是獲取了不少的主鍵,而不是全部的字段數據,相對而言效率會提高不少。code

相關文章
相關標籤/搜索