【发布时间】:2012-08-15 07:59:11
【问题描述】:
我一直在使用 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;
在那之后,我添加了近 200,000 行,其中 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
所以,使用了key,并且行数接近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 DOES 使用索引。
那么,我在这里没有看到什么?问题出在哪里?
感谢您的帮助。
【问题讨论】: