索引优化策略面试题

image.png

A:用了c1,c2,c3,c4(mysql没你傻,它知道在不影响语义的情况下换下顺序)

image.png

B:用了c1,c2,c3,而c4没有(在c3后就中断了)

image.png

C:用到了c1

image.png

如果是order by c2,c3 则用到了c1,而c2,c3用来排序了:

image.png

关于group by语句的过程:

image.png


例如下面的例子(未建立cat_id索引的情况下)就用到了临时表:

image.png

D:用了c1,但用上了c2,c3排序(因为Extra没有Using filesort),因为很巧,正好是按照c2,c3排序的。

image.png

而c2,c3调换顺序就不同了:用了c1,但c3,c2是用的filesort!

image.png

E:用上了c1,c2,没有用到filesort,说明order by c2,c3也发挥了作用

image.png

而,order by c2,c3倒过来,依然没用到filesort。因为c2已经等常量b了,还有啥好排序的,就只是order by c3了:

image.png

如果把c2='b'去掉,就有filesort排序了:

image.png






转载的:https://www.linuxidc.com/Linux/2014-11/109442.htm

MySQL优化之BTree索引使用规则

从一道题开始分析:

假设某个表有一个联合索引(c1,c2,c3,c4)一下——只能使用该联合索引的c1,c2,c3部分
A where c1=x and c2=x and c4>x and c3=x
B where c1=x and c2=x and c4=x order by c3
C where c1=x and c4= x group by c3,c2
D where c1=? and c5=? order by c2,c3
E where c1=? and c2=? and c5=? order by c2,c3

有谁知道下面A-E能否可以使用索引!!为什么?

OK;开始

创建表:

insert into t 
values
('a1','a2','a3','a4','a5'),
('b1','b2','b3','b4','b5');

插入数据:

insert into t 
values
('a1','a2','a3','a4','a5'),
('b1','b2','b3','b4','b5');

添加索引:

alter table t add index c1234(c1,c2,c3,c4);

对第一种情况:说明c1,c2,c3,c4被使用

MySQL优化之BTree索引使用规则

稍作改变:

MySQL优化之BTree索引使用规则

MySQL优化之BTree索引使用规则

使用group by 一般先生成临时文件,在进行排序

order by 哪?同上面类似啦

MySQL优化之BTree索引使用规则

稍微改变一下,分析:知道原理都很容易啦!

MySQL优化之BTree索引使用规则

上面问题答案是多少?反正我是不知道!

总结规律可得:

MySQL优化之BTree索引使用规则


猜你喜欢

转载自blog.51cto.com/5660061/2374613
今日推荐