MySQL的索引优化

本文详细探讨了MySQL索引的使用场景,包括全值匹配、查询范围、最左前缀等,同时也列举了不适合使用索引的情况,如以通配符开始的LIKE语句和OR语句。此外,还介绍了索引提示,如如何强制使用或忽略索引,以提高查询效率。
摘要由CSDN通过智能技术生成

一、索引的使用场景

1、全值匹配

通过主键索引查询

mysql> explain select * from t_goods where id = 1 \G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t_goods
   partitions: NULL
         type: const
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)

可以看到这里查询数据使用了主键索引。

现在我们再创建一个索引。

ALTER Table t_goods ADD INDEX index_category_name(t_category_id,t_name);

这里为t_category_id与t_name创建了联合索引。

mysql> explain select * from t_goods where t_category_id = 1 and t_name = '手机' \G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t_goods
   partitions: NULL
         type: ref
possible_keys: index_category_name
          key: index_category_name
      key_len: 208
          ref: const,const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)

这里的查询条件为t_category_id与t_name,所以查询时使用了联合索引index_category_name

2、查询范围

对索引的值进行范围查找

mysql> explain select * from t_goods where id >= 1 and id <=20 \G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t_goods
   partitions: NULL
         type: range
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: NULL
         rows: 15
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)

type: range说明根据主键索引范围进行查询。这里 Extra: Using where,说明MySQL按照主键确定范围后再回表查询数据。

3、匹配最左前缀

解释:也就是说,在使用索引时,MySQL优化器会根据查询条件使用该索引。只有满足这个匹配原则才会使用索引。例如过程创建的联合索引index_category_name(t_category_id, t_name),如果我跳过t_category_id直接使用t_name条件查询,那么这个查询将不会使用索引。

mysql> explain select * from t_goods where t_name='手机' \G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: t_goods
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 15
     filtered: 10.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)

可以看到这个查询并没有使用索引。

4、查询索引列

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值