mysql 联合索引查询规则

联合索引

explain select *
from test1
where   a = 1 and b = 2 and d = 20
  • 未建索引情况下:
  • image-20210422152031145
  • 建了abd索引的情况下:用上了abd的索引,而且长度为12,整个索引都用上了,type类型变为 ref
  • image-20210422152141655
explain select *
from test1
where   a = 1 and b > 2 and d = 20
  • 建了abd索引的情况下:在出现范围搜索的时候,还是用上了abd的索引,但是只用到了ab,长度为8,类型变为range

  • image-20210422152449820

explain select *
from test1
where   a = 1 and b = 2 ORDER BY d
  • 用上了order by 也可以使用索引,可以避免文件排序(file sort)但是索引长度显示为8,显示只用到了前两个,这可能是第三个直接提取出来了,不计入索引长度
  • image-20210422155116602
explain select *
from test1
where   a = 1 and d = 2 ORDER BY b
  • order by里的bd顺序颠倒,现在只用到了 abd索引里的ab,和范围搜索差不多的情况,后边的索引列用不上了
  • image-20210422155303073
explain select *
from test1
where   a = 1 and b = 2 or c = 2
ORDER BY d;
  • 出现了or这个东西,会导致整个abd索引失效
  • image-20210422155534107
explain select *
from test1
where   a = 1 and b = 2 or c = 2
ORDER BY d;

CREATE INDEX index_abd ON test1(a,b);  -- 建立ab索引
CREATE INDEX index_cd  ON  test1(c) --建立c索引
  • 分别对or语句左右两侧建立索引,可以用上索引,单独一边则不行,但都没加上d,出现了文件排序
  • image-20210422160054913
explain select *
from test1
where   a = 1 and b = 2 or c = 2
ORDER BY d;

CREATE INDEX index_abd ON test1(a,b,d); -- abd索引
CREATE INDEX index_cd  ON  test1(c,d)  -- cd索引
  • 同上一样,有or的情况没必要对排序的那列给加上,因为合并完还得排序,所以根本不需要对d加上索引

  • image-20210422160733718

你可能感兴趣的:(课内知识,mysql,数据库,sql)