mysql b-tree 索引下联合索引的顺序测试方案

时间:2022-01-23 19:29:24

使用联合索引需要注意的列顺序
比如在使用
select * from user where x=1 and y=2;
的时候,应该需要建立的索引可能是 add key(x,y)
如何确定索引的顺序
一般经验而言
可以使用
select count(distinct x)/count(x) as x_selectivity,
count(distinct y)/count(y) as x_selectivity,
count(*),
from user;
************************row1***************************
x_selectivity: 0.0001
y_selectivity: 0.0312
count(*) : 16022

在x中的选择性越高,所以可以放在第一列
alert table user add key(x,y);

另外可以在历史的慢查询中找到类似的进行优化

比如
select * from user where x=1 and y=2;

select sum(x=1),sum(y=2) from user\G;
******************row1**********************************
sum(x=1): 7992
sum(y=2): 30

y的选择性会更高一些,可以放在第一列

然后看看y=2 对应的x列的选择性
select sum(x=1) from user where y=2
******************row1**********************************
sum(x=1): 17

但是有可能mysql存在查询不公平的情况,服务器的整体性能可能更糟糕,,所以需要提取一下最差的查询进行这项的查询工作

这类工作被某些优化极客geek称为sarg。这是“可搜索参数(searchable argument)”的缩写。