Mysql索引合并(index merge)导致的死锁问题

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/loophome/article/details/82689841

在mysql5.0之前,一个表仅仅能使用一个索引,从5.1开始,引入了 index merge 优化技术,对同一个表可以使用多个索引分别进行条件扫描。

可以使用explain来查看index merge

Using intersect(idx_brand_id,idx_i_sort_id);

以上查询,使用了2个索引。大家也知道,mysql innodb引擎使用索引来实现行级别的锁,以下描述一下死锁发生的场景。

业务上需要更新排序值,采用事务来更新,而且更新前为i_sort_id添加了redis锁,但仍然有死锁的情况发生

事务A更新:

update * where i_sort_id=1 and brand_id=1
update * where i_sort_id=1 and brand_id=2

事务B更新:

update * where i_sort_id=2 and brand_id=2
update * where i_sort_id=2 and brand_id=1

由于更新使用了2个索引,idx_brand_id是造成死锁的关键。事务A更新了brand_id=1,但发现brand_id=2被事务B锁定,事务B发现brand_id=1被事务A锁定。2个事务均无法执行。

解决方案:

其实也很简单,为i_sort_id何brand_id建立复合索引即可。这个问题是由于索引建立不合理导致的,同时也没有考虑到index merge的影响。

有关索引合并的介绍,可以参考mysql的文档:

https://dev.mysql.com/doc/refman/5.7/en/index-merge-optimization.html

猜你喜欢

转载自blog.csdn.net/loophome/article/details/82689841