[MySQL] mysql優化實例-為join表關聯字段增加索引


在排查所有查詢語句效率的過程中 , 發現了join關聯表的時候 , 被驅動表沒有走索引而是進行的全表掃描

實際的sql語句如下:

explain select a.* from audit_rules a left join audit_rules_detail b on a.id=b.rule_id where a.ent_id=23684

輸出:

+----+-------------+-------+------+---------------+------------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key        | key_len | ref   | rows | Extra |
+----+-------------+-------+------+---------------+------------+---------+-------+------+-------+
|  1 | SIMPLE      | a     | ref  | idx_ent_id    | idx_ent_id | 4       | const |   12 |       |
|  1 | SIMPLE      | b     | ALL  | NULL          | NULL       | NULL    | NULL  |   35 |       |
+----+-------------+-------+------+---------------+------------+---------+-------+------+-------+

看到表b是全表掃描 , 這是因為b的字段rule_id沒有索引

增加上索引以后

+----+-------------+-------+------+---------------+-------------+---------+--------------+------+-------------+
| id | select_type | table | type | possible_keys | key         | key_len | ref          | rows | Extra       |
+----+-------------+-------+------+---------------+-------------+---------+--------------+------+-------------+
|  1 | SIMPLE      | a     | ref  | idx_ent_id    | idx_ent_id  | 4       | const        |   12 |             |
|  1 | SIMPLE      | b     | ref  | idx_rule_id   | idx_rule_id | 4       | sinanet.a.id |    1 | Using index |

MySQL是只支持一種JOIN算法Nested-Loop Join(嵌套循環鏈接)
當關聯字段有索引時,走的是Index Nested-Loop Join(索引嵌套鏈接)
沒有索引時會走,Block Nested-Loop Join比Simple Nested-Loop Join多了一個中間join buffer緩沖處理的過程

沒有索引時:

 

 

有索引時

 


免責聲明!

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



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