MySql中explain結果filtered的解釋


MySql explain語句的返回結果中,filtered字段要怎么理解?

MySql5.7官方文檔中描述如下:

The filtered column indicates an estimated percentage of table rows filtered by the table condition. The maximum value is 100, which means no filtering of rows occurred. Values decreasing from 100 indicate increasing amounts of filtering. rows shows the estimated number of rows examined and rows × filtered shows the number of rows joined with the following table. For example, if rows is 1000 and filtered is 50.00 (50%), the number of rows to be joined with the following table is 1000 × 50% = 500.

這段文字不是很好理解,舉例來說,有如下三個查詢語句的explain結果,針對b和c表的顯示filtered是100,而針對a表的顯示是18。

+-------------+-------+--------+---------+---------+------+----------+
| select_type | table | type   | key     | key_len | rows | filtered |
+-------------+-------+--------+---------+---------+------+----------+
| PRIMARY     | a     | range  | search  | 4       |  174 |   18.00  |
| PRIMARY     | b     | eq_ref | PRIMARY | 4       |    1 |   100.00 |
| PRIMARY     | c     | ALL    | PRIMARY | 4       |    1 |   100.00 |

我們可以怎么理解filtered的值呢?從filtered的值中得出什么結論呢?到底是100更好還是18更好?
首先,這里的filtered表示通過查詢條件獲取的最終記錄行數占通過type字段指明的搜索方式搜索出來的記錄行數的百分比。
以上圖的第一條語句為例,MySQL首先使用索引(這里的type是range)掃描表a,預計會得到174條記錄,也就是rows列展示的記錄數。接下來MySql會使用額外的查詢條件對這174行記錄做二次過濾,最終得到符合查詢語句的32條記錄,也就是174條記錄的18%。而18%就是filtered的值。
更完美的情況下,應該是使用某個索引,直接搜索出32條記錄並且過濾掉另外82%的記錄。
因此一個比較低filtered值表示需要有一個更好的索引,假如type=all,表示以全表掃描的方式得到1000條記錄,且filtered=0.1%,表示只有1條記錄是符合搜索條件的。此時如果加一個索引可以直接搜出來1條數據,那么filtered就可以提升到100%。
由此可見,filtered=100%確實是要比18%要好。

當然,filtered不是萬能的,關注執行計划結果中其他列的值並優化查詢更重要。比如為了避免出現filesort(使用可以滿足order by的索引),即使filtered的值比較低也沒問題。再比如上面filtered=0.1%的場景,我們更應該關注的是添加一個索引提高查詢性能,而不是看filtered的值。


免責聲明!

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



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