查詢優化 ORDER BY查詢優化

2022-04-21 09:38:36 字數 2591 閱讀 3848

mysql 系列文章主頁

order by 子句,盡量使用 index 查詢,避免使用 filesort 排序

盡可能在索引列上完成排序操作,遵照索引的最佳左字首原則

1 準備資料

1.1 建表

drop

table

ifexists

employee;

create

table

ifnot

exists

employee (

id intprimary

keyauto_increment,

age

int,

birth

timestamp

);

1.2 插入資料

insert

into employee(age, birth) values(22

, now());

insert

into employee(age, birth) values(23

, now());

insert

into employee(age, birth) values(24, now());

2 測試&explain分析

2.1 建立索引

create

index idx_agebirth on employee(age, birth);

2.2 測試

case#1:

explain select

*from employee where age >

20order

by age;

case#2:

explain select

*from employee where age >

20order

by age, birth;

case#3:

explain select

*from employee where age >

20order

by birth;

結果:出現了 using filesort

case#4:

explain select

*from employee where age >

20order

by birth, age;

結果:出現了 using filesort

case#5:

explain select

*from employee order

by birth;

結果:出現了 using filesort

case#6:

explain select

*from employee where birth >

'2018-01-01 00:00:00

'order

by birth;

結果:出現了 using filesort

case#7:

explain select

*from employee where birth >

'2018-01-01 00:00:00

'order

by age;

case#8:

explain select

*from employee order

by age asc, birth desc;

結果:出現了 using filesort

2.3 示例性總結

mysql支援兩種方式的排序,index和filesort,index效率高。它指mysql掃瞄索引本身完成排序。filesort效率較低。

order by 滿足兩情況,會使用index方式排序:

2.4 filesort的兩種排序演算法

2.4.1 雙路排序

mysql 4.1 之前使用的,兩次掃瞄磁碟

2.4.2 單路排序

是對雙路排序的改進演算法。

從磁碟讀取查詢需要的所有列,按照 order by 列在 buffer 中對它們進行排序,然後掃瞄排序後的列表進行輸出,它的效率更高一些,避免了兩次讀取資料。並且把隨機io變成了順序io,但是,它會使用更多的空間,因為它把每一行都儲存在記憶體中了。

但有可能出現「偷雞不成蝕把公尺」的問題(類似於 concurrent mode failure),這與 sort buffer 有很大關係(兩個引數:sort_buffer_size & max_length_for_sort_data)

2.5 group by

group by 實質是先排序後進行分組,遵照索引的最佳左字首原則

3 總結

order by 要盡量使用 index 排序,避免 filesort 排序

MySQL查詢優化之ORDER BY

select id from uc user baseinfo where area code 020 limit 0,10 執行成功,當前返回 10 行,耗時 109ms.select id from uc user baseinfo where area code 020 limit 10,10...

查詢優化(MySQL優化查詢)

關聯查詢太多join 設計缺陷或不得已的需求 資料庫伺服器調優及各個引數設定不適當 緩衝 執行緒數等 慢查詢日誌 找出執行速度慢的sql語句 慢查詢的開啟並捕獲 explain 慢sql分析 show profile查詢sql在mysql伺服器裡面的執行細節和生命週期情況 sql資料庫伺服器的引數調...

MySQL 優化 ORDER BY 優化

本文翻譯自mysql 官網 order by optimization,mysql 版本 5.7。這一部分描述了mysql何時會使用索引來滿足order by子句,filesort 操作會在索引不能生效的時候被用到,以及優化器對order by的執行計畫資訊。order by後面有沒有跟著limit...