问题:
我在表hutest的 c列创建了索引,事务A执行update hutest set a=‘11’ where c=6,这时事务B执行update hutest set a=‘22’ where c=5,按常理事务B是能执行的,因为c列有索引,但却发现事务b一直在等待锁无法执行
用explain发现事务b走的是索引c,但是事务A却走的主键primaryKey,导致整表被锁
开始分析:
从图中可知,并不是都用到了索引,有的用到了主键索引,所以会导致锁表的情况
问题分析:
官方文档原文
Each table index is queried, and the best index is used unless the optimizer believes that it is more efficient to use a table scan. At one time, a scan was used based on whether the best index spanned more than 30% of the table, but a fixed percentage no longer determines the choice between using an index or a scan. The optimizer now is more complex and bases its estimate on additional factors such as table size, number of rows, and I/O block size.
大致当扫描的数据超过30%时,优化器并不会一定二级索引会更高效,会认为主键索引,进行全表扫描更高效,
在实际中,发现并没到30%就用了全表扫描(可能跟数据量和msql的版本等等有关)
个人猜测:当筛选的列多了,使用了二级索引只是拿到了主键key的id值,还要回表去主键索引里查询,此时优化器认为这样的效率没有直接去主键索引中全表扫描查询效率高。
实际中c=6的一直是1w条,当总条数是2w时,where c=6用到是主键索引,但当总条数为13w时,用到了索引C列.
疑问1:
用limit的时候使用到了二级索引
疑问2:
explain出来的条数比count的多,进行插入删除操作,并不是删除导致的