[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       |
+----+-------------+-------+------+---------------+-------------+---------+--------------+------+-------------+
|  ref  | idx_ent_id    | idx_ent_id  | 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缓冲处理的过程

没有索引时:

 

 

有索引时

 

相关文章

优化MySQL数据库发布系统存储的方法有:1.mysql库主从读写分...
使用mysql的方法:在“我的电脑”→右键→“管理”→“服务”...
在mysql中查看root用户权限的方法:1.命令行启动mysql服务;...
MySQL主从复制是用来备份一个与主数据库一样环境的从数据库,...
运行mysql的方法1.启动mysql服务,在“我的电脑”→右键→“...
开启mysql的方法1.可以通过快捷键win+r,输入cmd,打开窗口,...