mysql join字段加索引_[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缓冲处理的过程

没有索引时:

2f351ee7e697bcea9b4bc275d00c0138.png

有索引时

353d7f65194150dcda75d5e6d336eb27.png

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值