我一直在使用MySQL(5.5.24,WinXP)上的索引进行实验,但我无法找到服务器在使用LIKE
时为什么不使用一个索引的原因。
例子如下:
我创建了一个测试表:
create table testTable (
id varchar(50) primary key,
text1 varchar(50) not null,
startDate varchar(50) not null
) ENGINE = innodb;
然后,我给 startDate
添加了一个索引。(请不要问为什么这个列是文本而不是日期时间...这只是一个简单的测试):
create index jeje on testTable(startdate);
analyze table testTable;
之后,我添加了将近20万行数据,其中startDate有3个可能的值。(每个值大约出现了三分之一,即近70,000次)
因此,如果我运行以下命令:EXPLAIN
explain select * from testTable use index (jeje) where startDate = 'aaaaaaaaa';
答案如下:
id = 1
select_type = SIMPLE
type = ref
possible_keys = jeje
key = jeje
rows = 88412
extra = Using where
所以,密钥被使用,并且行数接近200,000/3,所以一切都很好。
问题是,如果我将查询更改为:(只是将“=”更改为“LIKE”):
explain select * from testTable use index(jeje) where startDate LIKE 'aaaaaaaaa';
在这种情况下,答案是:
id = 1
select_type = SIMPLE
type = ALL
possible_keys = jeje
key = null
rows = 176824
extra = Using where
所以,索引现在没有被使用(键为空,并且接近于完整表...因为type=all建议)。MySQL文档称LIKE确实利用索引。
那么,我在这里看不到什么?问题出在哪里?
感谢您的帮助。