mysql组合索引与字段顺序学习

发布时间:2020-01-25编辑:脚本学堂
很多时候,我们在mysql中创建了索引,但是某些查询还是很慢,根本就没有使用到索引!
一般来说,可能是某些字段没有创建索引,或者是组合索引中字段的顺序与查询语句中字段

很多时候,我们在mysql中创建了索引,但是某些查询还是很慢,根本就没有使用到索引!
一般来说,可能是某些字段没有创建索引,或者是组合索引中字段的顺序与查询语句中字段的顺序不符。

看下面的例子:
假设有一张订单表(orders),包含order_id和product_id二个字段。
一共有31条数据。符合下面语句的数据有5条。

执行下面的sql语句
select product_id
from orders
where order_id in (123, 312, 223, 132, 224);

这条语句要mysql去根据order_id进行搜索,然后返回匹配记录中的product_id。

所以组合索引应该按照以下的顺序创建:
create index orderid_productid on orders(order_id, product_id)
mysql> explain select product_id from orders where order_id in (123, 312, 223, 132, 224) G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: orders
         type: range
possible_keys: orderid_productid
          key: orderid_productid
      key_len: 5
          ref: NULL
         rows: 5
        Extra: Using where; Using index
1 row in set (0.00 sec)

可以看到,这个组合索引被用到了,扫描的范围也很小,只有5行。

如果把组合索引的顺序换成product_id, order_id的话,
mysql就会去索引中搜索 *123 *312 *223 *132 *224,必然会有些慢了。
mysql> create index orderid_productid on orders(product_id, order_id);                                                     
Query OK, 31 rows affected (0.01 sec)
Records: 31  Duplicates: 0  Warnings: 0

mysql> explain select product_id from orders where order_id in (123, 312, 223, 132, 224) G

*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: orders
         type: index
possible_keys: NULL
          key: orderid_productid
      key_len: 10
          ref: NULL
         rows: 31
        Extra: Using where; Using index
1 row in set (0.00 sec)

这次索引搜索的性能显然不能和上次相比了。

rows:31,我的表中一共就31条数据。

索引被使用部分的长度:key_len:10,比上一次的key_len:5多了一倍。

不知道是这样在索引里面查找速度快,还是直接去全表扫描更快呢?
mysql> alter table orders add modify_a char(255) default 'aaa';
Query OK, 31 rows affected (0.01 sec)
Records: 31  Duplicates: 0  Warnings: 0

mysql>
mysql>
mysql> explain select modify_a from orders where order_id in (123, 312, 223, 132, 224) G        
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: orders
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 31
        Extra: Using where
1 row in set (0.00 sec)

这样就不会用到索引了。 刚才是因为select的product_id与where中的order_id都在索引里面的。

为什么要创建组合索引呢?这么简单的情况直接创建一个order_id的索引不就行了吗?
如果只有一个order_id索引,没什么问题,会用到这个索引,然后mysql要去磁盘上的表里面取到product_id。

如果有组合索引的话,mysql可以完全从索引中取到product_id,速度自然会快。

再多说几句组合索引的最左优先原则:
组合索引的第一个字段必须出现在查询组句中,这个索引才会被用到。
如果有一个组合索引(col_a,col_b,col_c)

下面的情况都会用到这个索引:
col_a = "some value";
col_a = "some value" and col_b = "some value";
col_a = "some value" and col_b = "some value" and col_c = "some value";
col_b = "some value" and col_a = "some value" and col_c = "some value";

对于最后一条语句,mysql会自动优化成第三条的样子~~。

下面的情况就不会用到索引:
col_b = "aaaaaa";
col_b = "aaaa" and col_c = "cccccc";