1. 程式人生 > >MySQL 中 filesort 優化

MySQL 中 filesort 優化

轉自:https://blog.csdn.net/shengqianfeng/article/details/80804218

用Explain分析SQL語句的時候,經常發現有的語句在Extra列會出現Using filesort,根據mysql官方文件對他的描述:

MySQL must do an extra pass to find out how to retrieve the rows in sorted order. The sort is done by going through all rows according to the join type and storing the sort key and pointer to the row for all rows that match the WHERE clause.

 中文手冊上翻譯的很彆扭:

“Mysql需要額外的一次傳遞,以找出如何按排序順序檢索行,通過根據聯接型別瀏覽所有行併為所有匹配where子句的行儲存排序關鍵字和行的指標來完成排序,然後關鍵字被排序,並按排序順序檢索行。”

 Using filesort 是Mysql裡一種速度比較慢的外部排序,儘量避免!

當where條件和order by同時出現時,如果where中欄位A使用了索引,而order by的欄位是B,檢視執行計劃時,就會出現filesort檔案排序。

解決這個問題就是建立一個包含 WHERE 和 ORDER BY 條件的混合索引。

比如:

建立一個sid和type的聯合索引:

再次檢視執行計劃:

filesort已經消失了!