暂无图片
几种索引失效总结
最近更新:2023-12-21 10:40:24

[[TOC]]

最常见的几种

  • 索引列上上使用函数 例如: select * from user where substring(name,1,2)='xxx'
  • 索引列上做运算 例如: select * from user where id-1=9
  • 前导模糊查询 例如: select * from user where name like "%雷%"
  • 使用了“非” 逻辑运算,<>、!=、not in 例如:select * from user where age <> 30
  • 使用 = 对NULL 做了比较 例如: select * from user where name = null
  • or条件中,存在没索引的列

字符串到数值型做隐式转换

因为在mysql当中, 字符串和数值类型之间可以互相进行隐式转换。 因此这种问题导致的索引失效很常见,也很容易被忽略。

  • 表结构和数据
root@dmysql 10:36:14 [swltest] > create table t1(id int, name varchar(32), key idx_name(name));
root@dmysql 10:36:56 [swltest] > create table t2(id int, name int, key idx_name(name));
root@dmysql 10:40:12 [swltest] > select * from t1;
+------+------+
| id   | name |
+------+------+
|    1 | 1    |
|    2 | 2    |
|    3 | 3    |
|    4 | 4    |
+------+------+
root@dmysql 10:40:12 [swltest] > select * from t2;
+------+------+
| id   | name |
+------+------+
|    1 | 1    |
|    2 | 2    |
|    3 | 3    |
|    4 | 4    |
+------+------+
  • 验证
-- 将t1作为驱动表, 使用name列做关联时, 可以使用t2表 name列上的索引
root@dmysql 10:40:00 [swltest] > explain select * from t1 join t2 on t1.name = t2.name where t1.id =1;
+----+-------------+-------+------------+------+---------------+----------+---------+-----------------+------+----------+-----------------------+
| id | select_type | table | partitions | type | possible_keys | key      | key_len | ref             | rows | filtered | Extra                 |
+----+-------------+-------+------------+------+---------------+----------+---------+-----------------+------+----------+-----------------------+
......