首页 > 其他 > 详细

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

时间:2020-06-18 11:58:55      阅读:60      评论:0      收藏:0      [点我收藏+]
某人曰,在数据检索的条件中使用!=操作符时,存储引擎会放弃使用索引。


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

通常情况下,这个说法是正确的。当然,也有特殊情况,话不能说绝对了。
有一个测试表共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 |
+------+--------+

 

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

原文:https://www.cnblogs.com/zhouwanchun/p/13156495.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!