mysql组合检索最左前缀_mysql - index 索引 之 联合索引的最左前缀原则

最左前缀原则:

简述:

查询条件中从索引的最左前列开始,并且不跳过索引中的某个列或多个列。

建表:

CREATE TABLE`index_test` (

`id`int(11) NOT NULLAUTO_INCREMENT,

`title`char(255) NOT NULL DEFAULT '' COMMENT 'title',

`content`text COMMENT 'text',

`c_time`bigint(20) NOT NULL DEFAULT '0' COMMENT 'create time',PRIMARY KEY(`id`),KEY `joint_index` (`title`,`content`(30),`c_time`) # 联合索引

) ENGINE=InnoDB DEFAULT CHARSET=utf8mb41 row in set (0.00 sec)

上表中,联合索引:

KEY `joint_index` (`title`,`content`(30),`c_time`)

原则解释:

最左列:查询条件中,必须包含 title(在查询条件中的位置,无要求),该联合索引才可以生效:包含 title,生效:

mysql> select title from index_test where title='123' and c_time=123456789;

c64f31810fb133a5596d2fcab2fcc96e.png

包含title,但未在查询条件的首位, 生效:

mysql> select title from index_test where c_time=123456789 and title='123';

40fb084f9ca2c3a33aaf8b5614325ce9.png

不包含title, 该联合索引,未生效:

mysql> select title from index_test where id=2 and c_time=123456789;

571aa889d682f94015c6a5ff92d06372.png

不跳过中间的某个列:生效:

mysql> select title, content, c_time from index_test where title='123' and content='wer';

e7b62c72b1b2706889358a51d5445c88.png

生效:

mysql> select title, content, c_time from index_test where title='123' and c_time=123456789 and content='wer';

ce69f4f089105b80bf2fd1039786e54a.png

失效(跳过content列):

mysql> select title, content, c_time from index_test where title='123' and c_time=123456789;

01a1607284fcbbe6f9b3c90dc969524e.png

联合索引的优势:

一个顶三个:

建了一个(a,b,c)的复合索引,那么实际等于建了(a),(a,b),(a,b,c)三个索引,因为每多一个索引,都会增加写操作的开销和磁盘空间的开销。

对于大量数据的表,这可是不小的开销!

覆盖索引:关键(避免了回表操作,减少IO操作)同样的有复合索引(a,b,c),如果有如下的sql:select a,b,c from table where a=1 and b = 1。那么MySQL可以直接通过遍历索引取得数据,而无需回表,这减少了很多的随机io操作。减少io操作,特别的随机io其实是dba主要的优化策略。所以,在真正的实际应用中,覆盖索引是主要的提升性能的优化手段之一

索引列越多,筛选出的数据约少(也就越精准)

mysql> explain select title from index_test where title='123' and c_time=123456789;+----+-------------+------------+------------+------+---------------+-------------+---------+-------+------+----------+--------------------------+| id | select_type | table      | partitions | type | possible_keys | key         | key_len | ref   | rows | filtered | Extra                    |+----+-------------+------------+------------+------+---------------+-------------+---------+-------+------+----------+--------------------------+|  1 | SIMPLE      | index_test | NULL       | ref  | joint_index   | joint_index | 1020    | const |    1 |   100.00 | Using where; Using index |+----+-------------+------------+------------+------+---------------+-------------+---------+-------+------+----------+--------------------------+1 row in set, 1 warning (0.01 sec)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值