MySQL百萬數據,你如何用分頁來查詢數據

在開發過程中我們經常會使用分頁,核心技術是使用limit進行數據的讀取,在使用limit進行分頁的測試過程中,得到以下數據:

select * from news order by id desc limit 0,10
耗時0.003秒
select * from news order by id desc limit 10000,10
耗時0.058秒
select * from news order by id desc limit 100000,10 
耗時0.575秒
select * from news order by id desc limit 1000000,10
耗時7.28秒

 我們驚訝的發現mysql在數據量大的情況下分頁起點越大查詢速度越慢,100萬條起的查詢速度已經需要7秒鐘。這是一個我們無法接受的數值!

 

改進方案 1

select * from news 
where id >  (select id from news order by id desc  limit 1000000, 1)
order by id desc 
limit 0,10

查詢時間 0.365秒,提升效率是非常明顯的!!原理是什麼呢???

我們使用條件對id進行了篩選,在子查詢 (select id from news order by id desc limit 1000000, 1) 中我們只查詢了id這一個字段比起select * 或 select 多個字段節省了大量的查詢開銷!

 

改進方案2

適合id連續的系統,速度極快!

select * from news 
where id  between 1000000 and 1000010 
order by id desc

不適合帶有條件的、id不連續的查詢。速度非常快!

 

百萬數據分頁的注意事項

接上一節,我們加上查詢條件:

select id from news 
where cate = 1
order by id desc 
limit 500000 ,10 

查詢時間 20 秒

好恐怖的速度!!利用上面方案進行優化:

select * from news
where cate = 1 and id > (select id from news where cate = 1 order by id desc limit 500000,1 ) 
order by id desc 
limit 0,10 

查詢時間 15 秒

優化效果不明顯,條件帶來的影響還是很大!在這樣的情況下無論我們怎麼去優化sql語句就無法解決運行效率問題。

那麼換個思路:建立一個索引表,只記錄文章的id、分類信息,我們將文章內容這個大字段分割出去。

表 news2 [ 文章表 引擎 myisam 字符集 utf-8 ]

-------------------------------------------------

id int 11 主鍵自動增加

cate int 11 索引

在寫入數據時將2張表同步,查詢是則可以使用news2 來進行條件查詢:

select * from news
where cate = 1 and id > (select id from news2 where cate = 1 order by id desc limit 500000,1 ) 
order by id desc 
limit 0,10

注意條件 id > 後面使用了news2 這張表!

運行時間 1.23秒,我們可以看到運行時間縮減了近20倍!!數據在10萬左右是查詢時間可以保持在0.5秒左右,是一個逐步接近我們能夠容忍的值!

但是1秒對於服務器來說依然是一個不能接受的值!!還有什麼可以優化的辦法嗎??

我們嘗試了一個偉大的變化:

將 news2 的存儲引擎改變爲innodb,執行結果是驚人的!

select * from news
where cate = 1 and id > (select id from news2 where cate = 1 order by id desc limit 500000,1 ) 
order by id desc 
limit 0,10

只需要 0.2秒,非常棒的速度。

到了這一步,我們的分頁優化完畢,顯然是有很大的效果的。你自己可以測試一下!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章