表數據量影響MySQL索引選擇

来源:https://www.cnblogs.com/clivewang/archive/2018/10/27/9863709.html
-Advertisement-
Play Games

現象 新建了一張員工表,插入了少量數據,索引中所有的欄位均在where條件出現時,正確走到了idx_nap索引,但是where出現部分自左開始的索引時,卻進行全表掃描,與MySQL官方所說的最左匹配原則“相悖”。 數據背景 sql CREATE TABLE ( int(11) NOT NULL AU ...


現象

新建了一張員工表,插入了少量數據,索引中所有的欄位均在where條件出現時,正確走到了idx_nap索引,但是where出現部分自左開始的索引時,卻進行全表掃描,與MySQL官方所說的最左匹配原則“相悖”。

數據背景

CREATE TABLE `staffs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(24) NOT NULL DEFAULT '' COMMENT '姓名',
  `age` int(11) NOT NULL DEFAULT '0' COMMENT '年齡',
  `pos` varchar(20) NOT NULL DEFAULT '' COMMENT '職位',
  `add_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '入職時間',
  PRIMARY KEY (`id`),
  KEY `idx_nap` (`name`,`age`,`pos`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COMMENT='員工記錄表';

表中數據如下:
id  name    age pos     add_time
1   July    23  dev     2018-06-04 16:02:02
2   Clive   22  dev     2018-06-04 16:02:32
3   Cleva   24  test    2018-06-04 16:02:38
4   July    23  test    2018-06-04 16:12:22
5   July    23  pre     2018-06-04 16:12:37
6   Clive   22  pre     2018-06-04 16:12:48
7   July    25  dev     2018-06-04 16:30:17

Explain語句看下執行計劃

-- 全匹配走了索引
explain select * from staffs where name = 'July' and age = 23 and pos = 'dev';
id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  staffs  NULL    ref idx_nap idx_nap 140 const,const,const   1   100.00  NULL

開啟優化器跟蹤優化過程

-- 左側部分匹配卻沒有走索引,全表掃描
explain select * from staffs where name = 'July' and age = 23;
id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  staffs2 NULL    ALL idx_nap NULL    NULL    NULL    6   50.00   Using where
-- 開啟優化器跟蹤
set session optimizer_trace='enabled=on';
-- 在執行完查詢語句後,在執行以下的select語句可以查看具體的優化器執行過程
select * from information_schema.optimizer_trace;

Trace部分的內容

{
  "steps": [
    {
      "join_preparation": {
        "select#": 1,
        "steps": [
          {
            "expanded_query": "/* select#1 */ select `staffs`.`id` AS `id`,`staffs`.`name` AS `name`,`staffs`.`age` AS `age`,`staffs`.`pos` AS `pos`,`staffs`.`add_time` AS `add_time` from `staffs` where ((`staffs`.`name` = 'July') and (`staffs`.`age` = 23))"
          }
        ]
      }
    },
    {
      "join_optimization": {
        "select#": 1,
        "steps": [
          {
            "condition_processing": {
              "condition": "WHERE",
              "original_condition": "((`staffs`.`name` = 'July') and (`staffs`.`age` = 23))",
              "steps": [
                {
                  "transformation": "equality_propagation",
                  "resulting_condition": "((`staffs`.`name` = 'July') and multiple equal(23, `staffs`.`age`))"
                },
                {
                  "transformation": "constant_propagation",
                  "resulting_condition": "((`staffs`.`name` = 'July') and multiple equal(23, `staffs`.`age`))"
                },
                {
                  "transformation": "trivial_condition_removal",
                  "resulting_condition": "((`staffs`.`name` = 'July') and multiple equal(23, `staffs`.`age`))"
                }
              ]
            }
          },
          {
            "substitute_generated_columns": {
            }
          },
          {
            "table_dependencies": [
              {
                "table": "`staffs`",
                "row_may_be_null": false,
                "map_bit": 0,
                "depends_on_map_bits": [
                ]
              }
            ]
          },
          {
            "ref_optimizer_key_uses": [
              {
                "table": "`staffs`",
                "field": "name",
                "equals": "'July'",
                "null_rejecting": false
              },
              {
                "table": "`staffs`",
                "field": "age",
                "equals": "23",
                "null_rejecting": false
              }
            ]
          },
          {
            "rows_estimation": [
              {
                "table": "`staffs`",
                "range_analysis": {
                  "table_scan": {
                    "rows": 6,
                    "cost": 4.3
                  },
                  "potential_range_indexes": [
                    {
                      "index": "PRIMARY",
                      "usable": false,
                      "cause": "not_applicable"
                    },
                    {
                      "index": "idx_nap",
                      "usable": true,
                      "key_parts": [
                        "name",
                        "age",
                        "pos",
                        "id"
                      ]
                    }
                  ],
                  "setup_range_conditions": [
                  ],
                  "group_index_range": {
                    "chosen": false,
                    "cause": "not_group_by_or_distinct"
                  },
                  "analyzing_range_alternatives": {
                    "range_scan_alternatives": [
                      {
                        "index": "idx_nap",
                        "ranges": [
                          "July <= name <= July AND 23 <= age <= 23"
                        ],
                        "index_dives_for_eq_ranges": true,
                        "rowid_ordered": false,
                        "using_mrr": false,
                        "index_only": false,
                        "rows": 3,
                        "cost": 4.61,
                        "chosen": false,
                        "cause": "cost"
                      }
                    ],
                    "analyzing_roworder_intersect": {
                      "usable": false,
                      "cause": "too_few_roworder_scans"
                    }
                  }
                }
              }
            ]
          },
          {
            "considered_execution_plans": [
              {
                "plan_prefix": [
                ],
                "table": "`staffs`",
                "best_access_path": {
                  "considered_access_paths": [
                    {
                    //可以看到這邊MySQL計算得到使用索引的成本為2.6
                      "access_type": "ref",
                      "index": "idx_nap",
                      "rows": 3,
                      "cost": 2.6,
                      "chosen": true
                    },
                    {
                    //而全表掃描計算所得的成本為2.2
                      "rows_to_scan": 6,
                      "access_type": "scan",
                      "resulting_rows": 6,
                      "cost": 2.2,
                      "chosen": true
                    }
                  ]
                },
                //因此選擇了成本更低的scan
                "condition_filtering_pct": 100,
                "rows_for_plan": 6,
                "cost_for_plan": 2.2,
                "chosen": true
              }
            ]
          },
          {
            "attaching_conditions_to_tables": {
              "original_condition": "((`staffs`.`age` = 23) and (`staffs`.`name` = 'July'))",
              "attached_conditions_computation": [
              ],
              "attached_conditions_summary": [
                {
                  "table": "`staffs`",
                  "attached": "((`staffs`.`age` = 23) and (`staffs`.`name` = 'July'))"
                }
              ]
            }
          },
          {
            "refine_plan": [
              {
                "table": "`staffs`"
              }
            ]
          }
        ]
      }
    },
    {
      "join_execution": {
        "select#": 1,
        "steps": [
        ]
      }
    }
  ]
}

增加表數據量

-- 接下來增大表的數據量
INSERT INTO `staffs` (`name`, `age`, `pos`, `add_time`)
VALUES
    ('July', 25, 'dev', '2018-06-04 16:30:17'),
    ('July', 23, 'dev1', '2018-06-04 16:02:02'),
    ('July', 23, 'dev2', '2018-06-04 16:02:02'),
    ('July', 23, 'dev3', '2018-06-04 16:02:02'),
    ('July', 23, 'dev4', '2018-06-04 16:02:02'),
    ('July', 23, 'dev6', '2018-06-04 16:02:02'),
    ('July', 23, 'dev5', '2018-06-04 16:02:02'),
    ('July', 23, 'dev7', '2018-06-04 16:02:02'),
    ('July', 23, 'dev8', '2018-06-04 16:02:02'),
    ('July', 23, 'dev9', '2018-06-04 16:02:02'),
    ('July', 23, 'dev10', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev1', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev2', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev3', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev4', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev6', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev5', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev7', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev8', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev9', '2018-06-04 16:02:02'),
    ('Clive', 23, 'dev10', '2018-06-04 16:02:02');

執行Explain

-- 再次執行同樣的查詢語句,會發現走到索引上了
explain select * from staffs where name = 'July' and age = 23;
id  select_type table   partitions  type    possible_keys   key key_len ref rows    filtered    Extra
1   SIMPLE  staffs  NULL    ref idx_nap idx_nap 78  const,const 13  100.00  NULL

查看新的Trace內容

-- 再看下優化器執行過程
{
  "steps": [
    {
      "join_preparation": {
        "select#": 1,
        "steps": [
          {
            "expanded_query": "/* select#1 */ select `staffs`.`id` AS `id`,`staffs`.`name` AS `name`,`staffs`.`age` AS `age`,`staffs`.`pos` AS `pos`,`staffs`.`add_time` AS `add_time` from `staffs` where ((`staffs`.`name` = 'July') and (`staffs`.`age` = 23))"
          }
        ]
      }
    },
    {
      "join_optimization": {
        "select#": 1,
        "steps": [
          {
            "condition_processing": {
              "condition": "WHERE",
              "original_condition": "((`staffs`.`name` = 'July') and (`staffs`.`age` = 23))",
              "steps": [
                {
                  "transformation": "equality_propagation",
                  "resulting_condition": "((`staffs`.`name` = 'July') and multiple equal(23, `staffs`.`age`))"
                },
                {
                  "transformation": "constant_propagation",
                  "resulting_condition": "((`staffs`.`name` = 'July') and multiple equal(23, `staffs`.`age`))"
                },
                {
                  "transformation": "trivial_condition_removal",
                  "resulting_condition": "((`staffs`.`name` = 'July') and multiple equal(23, `staffs`.`age`))"
                }
              ]
            }
          },
          {
            "substitute_generated_columns": {
            }
          },
          {
            "table_dependencies": [
              {
                "table": "`staffs`",
                "row_may_be_null": false,
                "map_bit": 0,
                "depends_on_map_bits": [
                ]
              }
            ]
          },
          {
            "ref_optimizer_key_uses": [
              {
                "table": "`staffs`",
                "field": "name",
                "equals": "'July'",
                "null_rejecting": false
              },
              {
                "table": "`staffs`",
                "field": "age",
                "equals": "23",
                "null_rejecting": false
              }
            ]
          },
          {
            "rows_estimation": [
              {
                "table": "`staffs`",
                "range_analysis": {
                  "table_scan": {
                    "rows": 27,
                    "cost": 8.5
                  },
                  "potential_range_indexes": [
                    {
                      "index": "PRIMARY",
                      "usable": false,
                      "cause": "not_applicable"
                    },
                    {
                      "index": "idx_nap",
                      "usable": true,
                      "key_parts": [
                        "name",
                        "age",
                        "pos",
                        "id"
                      ]
                    }
                  ],
                  "setup_range_conditions": [
                  ],
                  "group_index_range": {
                    "chosen": false,
                    "cause": "not_group_by_or_distinct"
                  },
                  "analyzing_range_alternatives": {
                    "range_scan_alternatives": [
                      {
                        "index": "idx_nap",
                        "ranges": [
                          "July <= name <= July AND 23 <= age <= 23"
                        ],
                        "index_dives_for_eq_ranges": true,
                        "rowid_ordered": false,
                        "using_mrr": false,
                        "index_only": false,
                        "rows": 13,
                        "cost": 16.61,
                        "chosen": false,
                        "cause": "cost"
                      }
                    ],
                    "analyzing_roworder_intersect": {
                      "usable": false,
                      "cause": "too_few_roworder_scans"
                    }
                  }
                }
              }
            ]
          },
          {
            "considered_execution_plans": [
              {
                "plan_prefix": [
                ],
                "table": "`staffs`",
                "best_access_path": {
                  "considered_access_paths": [
                    {
                    //使用索引的成本變為了5.3
                      "access_type": "ref",
                      "index": "idx_nap",
                      "rows": 13,
                      "cost": 5.3,
                      "chosen": true
                    },
                    {
                    //scan的成本變為了6.4
                      "rows_to_scan": 27,
                      "access_type": "scan",
                      "resulting_rows": 27,
                      "cost": 6.4,
                      "chosen": false
                    }
                  ]
                },
                //使用索引查詢的成本更低,因此選擇了走索引
                "condition_filtering_pct": 100,
                "rows_for_plan": 13,
                "cost_for_plan": 5.3,
                "chosen": true
              }
            ]
          },
          {
            "attaching_conditions_to_tables": {
              "original_condition": "((`staffs`.`age` = 23) and (`staffs`.`name` = 'July'))",
              "attached_conditions_computation": [
              ],
              "attached_conditions_summary": [
                {
                  "table": "`staffs`",
                  "attached": null
                }
              ]
            }
          },
          {
            "refine_plan": [
              {
                "table": "`staffs`"
              }
            ]
          }
        ]
      }
    },
    {
      "join_execution": {
        "select#": 1,
        "steps": [
        ]
      }
    }
  ]
}

結論

MySQL表數據量的大小,會影響索引的選擇,具體的情況還是通過Explain和Optimizer Trace來查看與分析。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 安裝redis 部署集群 參考資料 https://www.cnblogs.com/it-cen/p/4295984.html https://blog.csdn.net/naixiyi/article/details/51346880 https://www.cnblogs.com/Patrick ...
  • mkfs 在磁碟分區上創建ext2、ext3、ext4、ms-dos、vfat文件系統,預設情況下會創建ext2。mkfs用於在設備上構建Linux文件系統,通常是硬碟分區。文件要麼是設備名稱(例如/dev/hda1,/dev/sdb2),要麼是包含文件系統的常規文件。成功返回0,失敗返回1。 實際 ...
  • 有時候,管理員終端登陸了系統,如果離開沒有退出賬戶,則會有安全隱患存在,因此需要優化終端超時。 設置終端超時: export TMOUT=10 永久生效: echo "export TMOUT=600" >>/etc/profile source /etc/profile 檢查是否生效: ...
  • 目的:表操作(表維護) 一、一對一(略過) 二、一對 1、建表原則:在多的一方創建外鍵指向一的一方的外鍵 2、建表:實體中添加 3、操作 1、參數: name屬性:集合屬性名 column屬性: 外鍵列名 class屬性: 與我關聯的對象完整類名 2、級聯操作: cascade save-updat ...
  • Spark 中有兩個類似的api,分別是 reduceByKey 和 groupByKey 。這兩個的功能類似,但底層實現卻有些不同,那麼為什麼要這樣設計呢?我們來從源碼的角度分析一下。 先看兩者的調用順序(都是使用預設的Partitioner,即defaultPartitioner) 所用 spa ...
  • 【前言】在配置主從的時候經常會用到這兩個語句,剛開始的時候還不清楚這兩個語句的使用特性和使用場景。 經過測試整理了以下文檔,希望能對大家有所幫助; 【一】RESET MASTER參數 功能說明:刪除所有的binglog日誌文件,並將日誌索引文件清空,重新開始所有新的日誌文件。用於第一次進行搭建主從庫 ...
  • 在查詢了很多資料以後,發現國內外沒有一篇關於hadoop2集群環境搭建的詳細步驟的文章。 所以,我想把我知道的分享給大家,方便大家交流。 ...
  • 一 .概述 SQL Server 將某些系統事件和用戶定義事件記錄到 SQL Server 錯誤日誌和 Microsoft Windows 應用程式日誌中。 這兩種日誌都會自動給所有記錄事件加上時間戳。 使用 SQL Server 錯誤日誌中的信息可以解決SQL Server的相關問題。 查看 SQ ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...