MySQL 如何不使用OFFSET而進行高速分頁

2021-08-01 20:40:13 字數 2275 閱讀 3884

談到要把查詢結果分頁顯示,下面的sql語句幾乎就是毋庸置疑的標準答案了。

select * from samples order by id limit 5 offset 30 

select * from samples order by id limit 30, 5

但是要警惕offset關鍵字的使用,因為它會造成相當一部分的多餘查詢。(查詢實際上會嘗試獲取offset之前的所有資料+offset之後limit個資料,並只擷取後半部分返回)。下面介紹的方法將能幫你避免前半部分的多餘查詢:

直接使用between關鍵字查詢指定區間即可。

select * from samples where id between 30-1 and 30+5 order by id

select * from samples where id between 30-5 and 30+1 order by id

基本思路是使用limit限制兩個方向的搜尋範圍,再用union all將兩個方向的搜尋結果合併。需要注意的是使用了order by得到的結果不能直接進行union運算,需要在外層再包一層select

select * from (

select * from samples where id < 30 order by id desc limit 1

)union all

select * from (

select * from samples where id >= 30 order by id asc limit 5+1)

select * from (

select * from samples where id > 30 order by id asc limit 1

)union all

select * from (

select * from samples where id <= 30 order by id desc limit 5+1

)這時候就要出動復合索引了,假設篩選目標包括更新時間id,優先比較更新時間,如果更新時間相同再比較id號。sql語句如下:

#建立索引

create index index_updated_at_and_id on posts(updated_at, id);

select * from (

select * from posts

where updated_at = '2017-01-01 00:00:00' and id > 30

or updated_at > '2017-01-01 00:00:00'

order by updated_at asc, id asc

limit 1

)union all

select * from (

select * from posts

where updated_at = '2017-01-01 00:00:00' and id <= 30

or updated_at < '2017-01-01 00:00:00'

order by updated_at desc, id desc

limit 5+1)

select * from (

select * from posts

where updated_at = '2017-01-01 00:00:00' and id < 30

or updated_at < '2017-01-01 00:00:00'

order by updated_at desc, id desc

limit 1

)union all

select * from (

select * from posts

where updated_at = '2017-01-01 00:00:00' and id >= 30

or updated_at > '2017-01-01 00:00:00'

order by updated_at asc, id asc

limit 5+1

)

如何不使用Bootstrap實現響應式

當你已經完成了無響應的 做的第一件事是在你的 html 頁面,貼上下面的 到頭部標籤之間。這將設定螢幕按1 1的尺寸顯示,在iphone 和其他智慧型手機的瀏覽器提供 全檢視瀏覽,並禁止使用者縮放頁面。的簡單解釋 第乙個meta width 控制 viewport 的大小,可以指定的乙個值,如果 6...

MySQL查詢不使用索引彙總

mysql查詢不使用索引彙總 眾所周知,增加索引是提高查詢速度的有效途徑,但是很多時候,即使增加了索引,查詢仍然不使用索引,這種情況嚴重影響效能,這裡就簡單總結幾條mysql不使用索引的情況 如果mysql估計使用索引比全表掃瞄更慢,則不使用索引。例如,如果列key均勻分布在1和100之間,下面的查...

MySQL查詢不使用索引彙總

眾所周知,增加索引是提高查詢速度的有效途徑,但是很多時候,即使增加了索引,查詢仍然不使用索引,這種情況嚴重影響效能,這裡就簡單總結幾條mysql不使用索引的情況 如果mysql估計使用索引比全表掃瞄更慢,則不使用索引。例如,如果列key均勻分布在1和100之間,下面的查詢使用索引就不是很好 sele...