MySQL 执行计划(Using where,Using index 和 Using index condition)

您所在的位置:网站首页 执行是什么意思女孩 MySQL 执行计划(Using where,Using index 和 Using index condition)

MySQL 执行计划(Using where,Using index 和 Using index condition)

2024-07-09 12:29| 来源: 网络整理| 查看: 265

关于执行计划的 Extra 字段,对这几个取值有一些疑惑,我说一下我的大致理解。

Using where:表示优化器需要通过索引回表查询数据;

Using index:表示直接访问索引就足够获取到所需要的数据,不需要通过索引回表;

Using index condition:在5.6版本后加入的新特性(Index Condition Pushdown);  Using index condition 会先条件过滤索引,过滤完索引后找到所有符合索引条件的数据行,随后用 WHERE 子句中的其他条件去过滤这些数据行;

Using where && Using index:这个确实不了解它和 Using index condition 的区别。

然后,我在 MySQL 的示例数据库 Sakila 中做了一些测试,但是结果却让我感到非常疑惑:

测试使用 Sakila.rental 表,表中的 customer_id 建立了名为 idx_fk_customer_id 索引。

-- 第一个 SQL 语句 EXPLAIN SELECT customer_id FROM rental WHERE customer_id>=300;

结果是使用了 idx_fk_customer_id 索引,但是 Extra 信息竟然为 Using where;Using index;在这个 SQL 语句中,SELECT 子句 和 WHERE 子句不是都是可以从索引中过滤并取得的吗,为什么Extra 的值不是 Using index 呢?

-- 第二个 SQL 语句 EXPLAIN SELECT * FROM rental WHERE customer_id>=373;

这回更奇怪了,因为 SELECT 语句中包含索引中不存在的数据,所以需要通过索引回表查询数据,所以 Extra 为 Using where 我可以理解,但是这里竟然 type 竟然为 ALL,也就说执行计划中使用的是全表扫描!这又是为什么呢?

-- 第三个 SQL 语句 EXPLAIN SELECT customer_id FROM rental WHERE customer_id>=373 AND customer_id=373 AND customer_id373 或者 customer_id=300;会使用索引, 而 EXPLAIN SELECT * FROM rental WHERE customer_id>=300; 则不会使用索引呢?

EXPLAIN SELECT * FROM rental WHERE customer_id>=300 AND customer_id=300 AND customer_id=, mysql 如果用index查找 则 会有 太多的 random disk IO. 所以它选择了 全表读. https://dev.mysql.com/doc/refman/5.6/en/how-to-avoid-table-scan.html

You are using a key with low cardinality (many rows match the key value) through another column. In this case, MySQL assumes that by using the key it probably will do many key lookups and that a table scan would be faster.

查以下 customer_id>=300 AND customer_id=300 AND customer_id= ;

优化器会在索引存在的情况下,通过符合 RANGE 范围的条数和总数的比例来选择是使用索引还是进行全表遍历

例如,在 rental 表中,表的总行数为 16044 行;

-- 不使用索引 EXPLAIN SELECT * FROM rental WHERE customer_id>492; -- 使用索引 EXPLAIN SELECT * FROM rental WHERE customer_id>493; -- 其中 id > 492 的行数为 2772, id > 493 的行数为 2749 -- 不使用索引 EXPLAIN SELECT * FROM rental WHERE customer_id100 AND customer_id < 201;

结论:当需要读取的数据超过一个临界值时,优化器会放弃从索引中读取而改为进行全表扫描,这是为了避免过多的 random disk.



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3