mysql索引 最佳_MySQL-mysql建立最佳索引

索引建立不是越多越好,我觉得只在 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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值