mysql之多列索引

mysql的多列索引是经常会遇到的问题,怎样才能有效命中索引,是本文要探讨的重点。

 

多列索引使用的Btree,也就是平衡二叉树。简单来说就是排好序的快速索引方式。它的原则就是要遵循左前缀索引。

多个索引从左边往右都使用上,才能使用到整个多列索引。

 

下面我先建立一个简单的表做实验:

create table t6 (

c1 char(1) not null default '',

c2 char(1) not null default '',

c3 char(1) not null default '',

c4 char(1) not null default '',

c5 char(1) not null default '',

key(c1,c2,c3,c4,c5)

) engine myisam charset utf8;

再分别insert into一些数据。

 

分别做以下一些查询:

1.

explain select * from t6 where c1='a' and c2='b' and c4>'a' and c3="c" \G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t6
type: range
possible_keys: c1
key: c1
key_len: 12
ref: NULL
rows: 2
Extra: Using where
1 row in set (0.00 sec)

这里使用到了c1,c2,c3,c4索引,特别c4是一个范围查询,所以type为range,依次c1,c2,c3被命中索引。

2.

explain select * from t6 where c1='a' and c4='a' order by c3,c2 \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t6
type: ref
possible_keys: c1
key: c1
key_len: 3
ref: const
rows: 2
Extra: Using where; Using filesort
1 row in set (0.00 sec)

过程中先命中了c1,然后在order by c3,c2的时候由于先去use c3做排序,从而联合索引断了。using filesort表明没有使用到多列合索引,而是做了文件内排序。

 

3.

explain select * from t6 where c1='a' and c4='a' order by c2,c3 \G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: t6
type: ref
possible_keys: c1
key: c1
key_len: 3
ref: const
rows: 2
Extra: Using where
1 row in set (0.00 sec)

 

反之命中c1索引后,先用c2排序,再是c3来排序,分别命中,最后是c4='a'做where查询,使用到了多列索引。

posted @   freephp  阅读(350)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示