某人曰,在数据检索的条件中使用!=操作符时,存储引擎会放弃使用索引。

某人曰,在数据检索的条件中使用!=操作符时,存储引擎会放弃使用索引。


理由:因为检索的范围不能确定,所以使用索引效率不高,会被引擎自动改为全表扫描。你认可他的说法吗?

通常情况下,这个说法是正确的。当然,也有特殊情况,话不能说绝对了。
有一个测试表共80万条数据,其中type列只有1、2两个值,分别占比97%和3%。
这种情况下,查询条件 WHERE type != 1,是有可能也可以走索引的。

下面是两个SQL的执行计划:
mysql> desc select * from t1 where type = 1\G
************ 1. row ************
id: 1
select_type: SIMPLE
table: t1
partitions: NULL
type: ref
possible_keys: type
key: type
key_len: 4
ref: const
rows: 399731
filtered: 100.00
Extra: NULL

mysql> desc select * from t1 where type != 1\G
************ 1. row ************
id: 1
select_type: SIMPLE
table: t1
partitions: NULL
type: ref
possible_keys: type
key: type
key_len: 4
ref: const
rows: 10182
filtered: 100.00
Extra: NULL

type数据分布
mysql> select type, count(*) as cnt from t1 group by type order by cnt;
+------+--------+
| type | cnt    |
+------+--------+
| 2    | 38304  |
| 1    | 761690 |
+------+--------+

 

posted @ 2020-06-18 11:04  捧花大王  阅读(194)  评论(0)    收藏  举报