Heim  >  Artikel  >  Backend-Entwicklung  >  mysql组合索引使用的问题

mysql组合索引使用的问题

WBOY
WBOYOriginal
2016-06-06 20:32:361170Durchsuche

最近在看mysql的索引使用 ,在到组合索引时碰到了一个问题 :

在《高性能mysql》中提到 “如果查询中某个列是范围查询,则其右边所有的列都无法使用索引 。
where last_name='Smith' and first_name like 'j%' and dob='1976-12-23 ,这个查询只能使用索引的前两列 ”

在测试中发现 使用like进行范围查询后,后面的列仍可以使用索引

CREATE TABLE t (
c1 char(2) NOT NULL DEFAULT '',
c2 char(2) NOT NULL DEFAULT '',
c3 char(2) NOT NULL DEFAULT '',
c4 char(2) NOT NULL DEFAULT '',
c5 char(2) NOT NULL DEFAULT '',
KEY test_index (c1,c2,c3,c4)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
insert into t (c1, c2, c3, c4, c5) values('1','2','3','4','5');
insert into t (c1, c2, c3, c4, c5) values('a','c','df','d','f');
insert into t (c1, c2, c3, c4, c5) values('d','x','d','d','x');
insert into t (c1, c2, c3, c4, c5) values('s','s','df','','d');

EXPLAIN
SELECT * FROM t WHERE c1 = '1' AND c2 = "2" AND c3 LIKE '3%' AND c4 = '2'

上面语句测试的结果 key_len的长度依然是24,
但是按照书说的 c3 使用了like,属于一个范围查找, c4就不能用到索引了才对 ,可是测试的结果是C4也可以用到

mysql组合索引使用的问题

请问这个是什么原因呢 ???

回复内容:

最近在看mysql的索引使用 ,在到组合索引时碰到了一个问题 :

在《高性能mysql》中提到 “如果查询中某个列是范围查询,则其右边所有的列都无法使用索引 。
where last_name='Smith' and first_name like 'j%' and dob='1976-12-23 ,这个查询只能使用索引的前两列 ”

在测试中发现 使用like进行范围查询后,后面的列仍可以使用索引

CREATE TABLE t (
c1 char(2) NOT NULL DEFAULT '',
c2 char(2) NOT NULL DEFAULT '',
c3 char(2) NOT NULL DEFAULT '',
c4 char(2) NOT NULL DEFAULT '',
c5 char(2) NOT NULL DEFAULT '',
KEY test_index (c1,c2,c3,c4)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
insert into t (c1, c2, c3, c4, c5) values('1','2','3','4','5');
insert into t (c1, c2, c3, c4, c5) values('a','c','df','d','f');
insert into t (c1, c2, c3, c4, c5) values('d','x','d','d','x');
insert into t (c1, c2, c3, c4, c5) values('s','s','df','','d');

EXPLAIN
SELECT * FROM t WHERE c1 = '1' AND c2 = "2" AND c3 LIKE '3%' AND c4 = '2'

上面语句测试的结果 key_len的长度依然是24,
但是按照书说的 c3 使用了like,属于一个范围查找, c4就不能用到索引了才对 ,可是测试的结果是C4也可以用到

mysql组合索引使用的问题

请问这个是什么原因呢 ???

<code> c3 LIKE '3%'
</code>

你把这个换成 c3 LIKE '%3'看看!

like查询分为3种
1.%XXX
2.XXX%
3.%XXX%

以上3种只有第二种可以使用索引

因为test_index (c1,c2,c3,c4)是组合索引

这个我也觉得奇怪、但是mysql会对部分range的查询优化、让它后面的列也能中索引。但是这个我还不知道什么时候能被优化。想想like也属于range的,所以可能也是被mysql优化了吧。(优化这东西不可控的,还是严格点好)

在做面试题么? 真实场景会用到这么多的联合索引么?

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn