Die*_*ino 9 mysql indexing explain
我一直在玩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;
Run Code Online (Sandbox Code Playgroud)
然后,我添加了一个索引startDate.(请不要问为什么列是文本而不是日期时间..这只是一个简单的测试):
create index jeje on testTable(startdate);
analyze table testTable;
Run Code Online (Sandbox Code Playgroud)
之后,我添加了近200,000行,其中startDate有3个可能的值.(每个人的三分之一出现..近70,000次)
所以,如果我运行这样的EXPLAIN命令:
explain select * from testTable use index (jeje) where startDate = 'aaaaaaaaa';
Run Code Online (Sandbox Code Playgroud)
答案如下:
id = 1
select_type = SIMPLE
type = ref
possible_keys = jeje
key = jeje
rows = 88412
extra = Using where
Run Code Online (Sandbox Code Playgroud)
因此,使用密钥,行数接近200,000/3,所以一切正常.
问题是,如果我将查询更改为:(只需将'='转换为'LIKE'):
explain select * from testTable use index(jeje) where startDate LIKE 'aaaaaaaaa';
Run Code Online (Sandbox Code Playgroud)
在这种情况下,答案是:
id = 1
select_type = SIMPLE
type = ALL
possible_keys = jeje
key = null
rows = 176824
extra = Using where
Run Code Online (Sandbox Code Playgroud)
因此,该指数没有被现在用于(key为null,且行接近满table..as类型=所有建议).
MySQL文档说LIKE DOES使用索引.
那么,我在这里看不到什么?问题出在哪儿?
谢谢你的帮助.
如果索引导致访问超过30%的表行,则MySql可以忽略索引.您可以尝试FORCE INDEX [index_name],它将在任何情况下使用索引.
sysvar_max_seeks_for_key的值也会影响是否使用索引:
http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_seeks_for_key
尝试将此值更改为较小的数字.
在SO上搜索类似的请求.
根据Ubik 评论和数据更改,我发现:在这些情况下使用索引:
- explain select * from testTable force index jeje where startDate like 'aaaaaaadsfadsfadsfasafsafsasfsadsfa%';
- explain select * from testTable force index jeje where startDate like 'aaaaaaadsfadsfadsfasafsafsasfsadsfa%';
- explain select * from testTable force index jeje where startDate like 'aaa';
Run Code Online (Sandbox Code Playgroud)
但当我使用此查询时,索引并未被使用:
- explain select * from testTable force index jeje where startDate like 'aaaaaaaaa';
Run Code Online (Sandbox Code Playgroud)
基于在startDate列中所有值都具有相同长度(9 个字符)的事实,当我使用 LIKE 命令和 9 个字符常量进行查询时, MySQL可能由于某些性能算法而宁愿不使用这个原因,并且走到桌子旁。
我关心的是看看我在原来的测试中是否犯了某种错误,但现在我认为索引和测试是正确的,并且 MySQL 在某些情况下决定不使用索引......我将继续这。
对我来说,这是一项封闭的任务。如果有人想在主题中添加一些内容,欢迎您。