MYSQL 索引利用实践

1.索引越少越好
2.最窄的字段放在键的左边
3.避免file sort排序,临时表和表扫描.


mysql索引方式

FULLTEXT,HASH,BTREE,RTREE


常用索引的类型

主键索引(特殊的唯一索引)、唯一索引、普通索引、全文索引、组合索引(联合索引,多列索引)

 

创建索引的原则

1、以B数索引最左前缀的规则创建索引。

2、优先创建联合索引而不是单列索引 

3、创建索引时要考虑索引的基数(基数越大,重复值越少,越值得创建索引,比如(distinct column)/count(*)),并把基数大、散列程度好的列放在前面

4、避免创建冗余索引,比如A,B列,在A上创建一个索引,在B上创建另外一个索引,然后在AB列上创建一个联合索引,那么A/B列单独创建的索引就是冗余索引。

 

like查询以%开头无法使用索引

desc select   * from eload_goods where goods_sn like'%110634507'

 

like查询以%开头%结尾无法使用索引

desc select   * from eload_goods where goods_sn like'%110634507%'

 

Like查询后置%可以使用索引

desc select   * from eload_goods where goods_sn like'110634507%' 可以使用索引

 

Or 查询多个字段,条件字段必须同时加索引, 才能使用索引

desc select   * from eload_goods where goods_sn ='110634507'  or market_price>2

可以比对union all

 

两个字段同时加上索引

desc select   * from eload_goods where goods_sn ='110634507'  or click_count>2

 

查询条件包含 is null 无法使用索引

desc select   * from eload_order_info where promotion_code is null

 

联合索引最左条件使用范围查询无法使用索引

 desc select   * from eload_order_info where insure_fee>1 and Need_Traking_number=2

 

联合索引

 desc select   * from eload_order_info where insure_fee=1 and Need_Traking_number=2

 

联合索引向左原则使用第一个字段查询可以使用索引

 desc select   * from eload_order_info where insure_fee=1

 

联合索引最左原则单独用第二个字段查询无法使用索引

 desc select   * from eload_order_info where  Need_Traking_number=2

 

not in 无法使用索引

 desc select   * from eload_order_info where  user_id not in(1)

 

!= 或 <> 无法使用索引

 desc select   * from eload_order_info where  user_id !=1

 

表达示左侧计算无法使用索引

EXPLAIN select * from eload_order_info where FROM_UNIXTIME(add_time,'%Y-%m-%d') = '2018-06-20'


表达式右侧计算可以使用索引

EXPLAIN select * from eload_order_info where add_time >= UNIX_TIMESTAMP('2018-06-20') AND add_time <= UNIX_TIMESTAMP('2018-06-21')

 

索引字段类型为varchar,不加单引号不能使用索引

EXPLAIN select * from eload_order_info WHERE order_sn = 123;

 

强制索引和禁止某个索引

EXPLAIN select * from eload_order_info FORCE INDEX(order_sn) WHERE order_sn = 123;

EXPLAIN select * from eload_order_info IGNORE INDEX(order_sn) WHERE order_sn = 123;

猜你喜欢

转载自blog.csdn.net/luolaifa000/article/details/80843972