索引建立不是越多越好,我觉得只在 b 列上建立索引即可。
那么
where a = 11 and b = 22
where b = 22
where b > 33 order by c desc
以上三种查询都会用到索引,分别是:ref , ref, range
我觉得没必要在 bc列 建立联合索引,因为即使建立bc索引 where b > 33 order by c desc,排序方式也是 Using filesort ,也就说没有利用索引排序,同样是文件排序。
还有 我觉得也没有必要在ba列建联合索引,如果建立该索引只对where a = 11 and b = 22 有点作用,type 都是 ref, 不建立的话只是需要 使用条件再过滤结果。当然这个根据情况来定,如果 b 字段重复的值很多,那么在ba列建立索引有很大作用。
还有我认为不用修改查询条件的顺序为 b = 22 and a = 11
如果在 a 和 b 字段建立建立索引:
ALTER TABLE table_name ADD INDEX ab(a,b);
那么 b = 22 and a = 11 与 a = 22 and b = 11 执行计划是一样的,但是经过优化器优化过的sql,是与条件顺序相反的。结果如下:
mysql> alter table test add index ab(a,b);
mysql> explain extended select * from test where a=54 and b=12G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test
type: ref
possible_keys: ab
key: ab
key_len: 8
ref: const,const
rows: 1
Extra:
select `test`.`test`.`id` AS `id`,`test`.`test`.`a` AS `a`,`tes
t`.`test`.`b` AS `b`,`test`.`test`.`c` AS `c` from `test`.`test` where ((`test`.
`test`.`b` = 12) and (`test`.`test`.`a` = 54))
============================================================
mysql> explain extended select * from test where b=54 and a=12G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test
type: ref
possible_keys: ab
key: ab
key_len: 8
ref: const,const
rows: 1
Extra:
select `test`.`test`.`id` AS `id`,`test`.`test`.`a` AS `a`,`tes
t`.`test`.`b` AS `b`,`test`.`test`.`c` AS `c` from `test`.`test` where ((`test`.
`test`.`a` = 12) and (`test`.`test`.`b` = 54))