mysql索引最左匹配原则的理解

本文探讨了MySQL的索引最左匹配原则,并通过执行计划和trace工具揭示了查询执行过程中可能存在的差异。尽管AND条件顺序不影响索引选择,但优化器会根据实际情况决定使用哪个索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

这里需要提醒的是:mysql的执行计划和查询的实际执行过程并不完全吻合。如何证明这一点呢?
真正的执行过程可以通过mysql的trace工具来分析。

1,针对执行2

EXPLAIN SELECT * FROM student WHERE   cid=1;

这里只显示trace结果的一部分内容:

{
            "considered_execution_plans": [
              {
                "plan_prefix": [
                ] /* plan_prefix */,
                "table": "`student`",
                "best_access_path": {
                  "considered_access_paths": [
                    {
                      "access_type": "scan",
                      "rows": 1,
                      "cost": 1.2,
                      "chosen": true
                    }
                  ] /* considered_access_paths */
                } /* best_access_path */,
                "cost_for_plan": 1.2,
                "rows_for_plan": 1,
                "chosen": true
              }
            ] /* considered_execution_plans */
          },

可以看到并没有使用索引,而是进行了全表扫描。
2,下面再来看一下执行1的trace:

 {
            "considered_execution_plans": [
              {
                "plan_prefix": [
                ] /* plan_prefix */,
                "table": "`student`",
                "best_access_path": {
                  "considered_access_paths": [
                    {
                      "access_type": "ref",
                      "index": "name_cid_INX",
                      "rows": 1,
                      "cost": 1.2,
                      "chosen": true
                    },
                    {
                      "access_type": "ref",
                      "index": "name_INX",
                      "rows": 1,
                      "cost": 1.2,
                      "chosen": false
                    },
                    {
                      "access_type": "scan",
                      "cause": "covering_index_better_than_full_scan",
                      "chosen": false
                    }
                  ] /* considered_access_paths */
                } /* best_access_path */,
                "cost_for_plan": 1.2,
                "rows_for_plan": 1,
                "chosen": true
              }
            ] /* considered_execution_plans */
          },

可以看出最终使用的索引是name_cid_INX。

王珊《数据库系统概论》(第5版)网授精讲班【教材精讲+考研真题串讲】
3,where中and条件的先后顺序对如何选择索引是无关的。因为优化器会去分析判断选用哪个索引。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值