MySQL order by 排序的兩種方式以及排序原理


MySQl innodb引擎支持創建索引(主鍵 唯一 聯合等)。

在實際的開發過程中,使用最多的還是聯合索引,使用聯合索引必須遵從最左前綴原則,比如,索引結構是 name_age_position。

1.在where條件中 如果使用到這三個字段作為條件,如where name=? and age=? and posision=? ;最好是按照索引創建的先后順序,雖然 where age=? and name=? and posision=? 這樣也會走name_age_position索引,但是,MySQL優化器需要耗時去把sql優化成where name=? and age=? and posision=? 這樣的格式來執行,浪費時間,這是不必要的

2.查詢盡可能多的讓條件走name_age_position索引,比如 where name=? and age>?and posision=?   這樣的查詢 只會用到name和age索引,不會使用posision索引

3.order by,如果where和order by 子句能滿足索引最左前綴法則,那么會使用索引排序,效率高  比如  where name=? order by  age  ,posision  注意 order by posision,age 將不會走索引排序,這種排序方式稱之為 using index sort,

如果order by 不使用索引排序,name將會使用文件排序(file sort),效率低。文件排序有兩種方式:

  單路排序:一次性取出所有滿足條件行的數據,然后再sort buffer中進行排序,然后返回結果集給客戶端

  多路排序(回表排序):根據where條件和排序字段定位到滿足條件的行數據,取出數據行的id和排序字段到sort buffer中排序,然后根據排好序的id回表查詢其他所需要的字段數據

 

  sort buffer的大小默認是1M  可以修改 max_length_for_sort_buffer=1024(默認)的值控制sort buffer的大小  不推薦修改

 


免責聲明!

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



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