手把手教你MySQL查詢優化分析

前言

MySQL是關係性數據庫中的一種,查詢功能強,數據一致性高,數據安全性高,支持二級索引。但性能方面稍遜於非關係性數據庫,特別是百萬級別以上的數據,很容易出現查詢慢的現象。這時候需要分析查詢慢的原因,一般情況下是程序員sql寫的爛,或者是沒有鍵索引,或者是索引失效等原因導致的。

這時候MySQL 提供的 EXPLAIN 命令就尤其重要, 它可以對 SELECT 語句進行分析, 並輸出 SELECT 執行的詳細信息, 以供開發人員針對性優化.

而且就在查詢語句前加上 Explain 就成:

EXPLAIN SELECT * FROM customer WHERE id < 100;

準備

首先需要建立兩個測試用表及數據:

CREATE TABLE `customer` (  
  `id`   BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NOT NULL DEFAULT '',
  `age`  INT(11) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `name_index` (`name`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4

INSERT INTO customer (name, age) VALUES ('a', 1);
INSERT INTO customer (name, age) VALUES ('b', 2);
INSERT INTO customer (name, age) VALUES ('c', 3);
INSERT INTO customer (name, age) VALUES ('d', 4);
INSERT INTO customer (name, age) VALUES ('e', 5);
INSERT INTO customer (name, age) VALUES ('f', 6);
INSERT INTO customer (name, age) VALUES ('g', 7);
INSERT INTO customer (name, age) VALUES ('h', 8);
INSERT INTO customer (name, age) VALUES ('i', 9);
CREATE TABLE `orders` (
  `id`           BIGINT(20) unsigned NOT NULL AUTO_INCREMENT,
  `user_id`      BIGINT(20) unsigned NOT NULL DEFAULT 0,  `product_name` VARCHAR(50) NOT NULL DEFAULT '',
  `productor`    VARCHAR(30) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  KEY `user_product_detail_index` (`user_id`, `product_name`, `productor`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4

INSERT INTO orders (user_id, product_name, productor) VALUES (1, 'p1', 'WHH');
INSERT INTO orders (user_id, product_name, productor) VALUES (1, 'p2', 'WL');
INSERT INTO orders (user_id, product_name, productor) VALUES (1, 'p1', 'DX');
INSERT INTO orders (user_id, product_name, productor) VALUES (2, 'p1', 'WHH');
INSERT INTO orders (user_id, product_name, productor) VALUES (2, 'p5', 'WL');
INSERT INTO orders (user_id, product_name, productor) VALUES (3, 'p3', 'MA');
INSERT INTO orders (user_id, product_name, productor) VALUES (4, 'p1', 'WHH');
INSERT INTO orders (user_id, product_name, productor) VALUES (6, 'p1', 'WHH');
INSERT INTO orders (user_id, product_name, productor) VALUES (9, 'p8', 'TE');

EXPLAIN 輸出格式

EXPLAIN 命令的輸出內容大致如下:

mysql> explain select * from customer where id = 1\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: const
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 8
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)

各列的含義如下:

  • id: SELECT 查詢的標識符. 每個 SELECT 都會自動分配一個唯一的標識符
  • List item
  • select_type: SELECT 查詢的類型
  • table: 查詢的是哪個表
  • partitions: 匹配的分區
  • type: join 類型
  • possible_keys: 此次查詢中可能選用的索引
  • key: 此次查詢中確切使用到的索引
  • ref: 哪個字段或常數與 key 一起被使用
  • rows: 顯示此查詢一共掃描了多少行. 這個是一個估計值
  • filtered: 表示此查詢條件所過濾的數據的百分比
  • extra: 額外的信息

接下來我們來重點看一下比較重要的幾個字段.

select_type

  • SIMPLE —— 簡單的select 查詢,查詢中不包含子查詢或者UNION
  • PRIMARY —— 查詢中若包含任何複雜的子查詢,最外層查詢則被標記爲primary
  • UNION —— 表示此查詢是 UNION 的第二或隨後的查詢
  • DEPENDENT UNION —— UNION 中的第二個或後面的查詢語句, 取決於外面的查詢
  • UNION RESULT —— 從UNION表獲取結果的select結果
  • DERIVED —— 在from列表中包含的子查詢被標記爲derived(衍生)MySQL會遞歸執行這些子查詢,把結果放在臨時表裏。
  • SUBQUERY —— 在select或where 列表中包含了子查詢
  • DEPENDENT SUBQUERY —— 子查詢中的第一個 SELECT, 取決於外面的查詢. 即子查詢依賴於外層查詢的結果.

最常見的查詢類別應該是 SIMPLE 了, 比如當我們的查詢沒有子查詢, 也沒有 UNION 查詢時, 那麼通常就是 SIMPLE 類型, 例如:

mysql> explain select * from customer where id = 2\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: const
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 8
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)

如果我們使用了 UNION 查詢, 那麼 EXPLAIN 輸出 的結果類似如下:

mysql> EXPLAIN (SELECT * FROM customer  WHERE id IN (1, 2, 3))    
    -> UNION
    -> (SELECT * FROM customer WHERE id IN (3, 4, 5));
+----+--------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-----------------+
| id | select_type  | table      | partitions | type  | possible_keys | key     | key_len | ref  | rows | filtered | Extra           |
+----+--------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-----------------+
|  1 | PRIMARY      | customer  | NULL       | range | PRIMARY       | PRIMARY | 8       | NULL |    3 |   100.00 | Using where     |
|  2 | UNION        | customer  | NULL       | range | PRIMARY       | PRIMARY | 8       | NULL |    3 |   100.00 | Using where     |
| NULL | UNION RESULT | <union1,2> | NULL       | ALL   | NULL          | NULL    | NULL    | NULL | NULL |     NULL | Using temporary |
+----+--------------+------------+------------+-------+---------------+---------+---------+------+------+----------+-----------------+
3 rows in set, 1 warning (0.00 sec)

table

表示查詢涉及的表或衍生表

type

type 字段比較重要, 它提供了判斷查詢是否高效的重要依據依據. 通過 type 字段, 我們判斷此次查詢是 全表掃描 還是 索引掃描 等.

type 常用類型

type 常用的取值有:

  • system: 表中只有一條數據. 這個類型是特殊的 const 類型
  • const: 針對主鍵或唯一索引的等值查詢掃描, 最多隻返回一行數據. const 查詢速度非常快, 因爲它僅僅讀取一次即可.例如下面的這個查詢, 它使用了主鍵索引, 因此 type 就是 const 類型的.
mysql> explain select * from customer where id = 2\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: const
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 8
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
1 row in set, 1 warning (0.00 sec)
  • eq_ref: 此類型通常出現在多表的 join 查詢, 表示對於前表的每一個結果, 都只能匹配到後表的一行結果. 並且查詢的比較操作通常是 =, 查詢效率較高. 例如:
mysql> EXPLAIN SELECT * FROM customer, order_info WHERE customer.id = order_info.user_id\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: order_info
   partitions: NULL
         type: index
possible_keys: user_product_detail_index
          key: user_product_detail_index
      key_len: 314
          ref: NULL
         rows: 9
     filtered: 100.00
        Extra: Using where; Using index
*************************** 2. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: eq_ref
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 8
          ref: test.order_info.user_id
         rows: 1
     filtered: 100.00
        Extra: NULL
2 rows in set, 1 warning (0.00 sec)
  • ref: 此類型通常出現在多表的 join 查詢, 針對於非唯一或非主鍵索引, 或者是使用了 最左前綴 規則索引的查詢.

例如下面這個例子中, 就使用到了 ref 類型的查詢:

mysql> EXPLAIN SELECT * FROM customer, order_info WHERE customer.id = order_info.user_id AND order_info.user_id = 5\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: const
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 8
          ref: const
         rows: 1
     filtered: 100.00
        Extra: NULL
*************************** 2. row ***************************
           id: 1
  select_type: SIMPLE
        table: order_info
   partitions: NULL
         type: ref
possible_keys: user_product_detail_index
          key: user_product_detail_index
      key_len: 9
          ref: const
         rows: 1
     filtered: 100.00
        Extra: Using index
2 rows in set, 1 warning (0.01 sec)

  • range: 表示使用索引範圍查詢, 通過索引字段範圍獲取表中部分數據記錄. 這個類型通常出現在 =, <>, >, >=, <, <=, IS NULL, <=>, BETWEEN, IN() 操作中.

當 type 是 range 時, 那麼 EXPLAIN 輸出的 ref 字段爲 NULL, 並且 key_len 字段是此次查詢中使用到的索引的最長的那個.

例如下面的例子就是一個範圍查詢:

mysql> EXPLAIN SELECT * FROM customer WHERE id BETWEEN 2 AND 8 \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: range
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 8
          ref: NULL
         rows: 7
     filtered: 100.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)
  • index: 表示全索引掃描(full index scan), 和 ALL 類型類似, 只不過 ALL 類型是全表掃描, 而 index 類型則僅僅掃描所有的索引, 而不掃描數據.

index 類型通常出現在: 所要查詢的數據直接在索引樹中就可以獲取到, 而不需要掃描數據. 當是這種情況時, Extra 字段 會顯示 Using index.

例如:

mysql> EXPLAIN SELECT name FROM  customer \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: index
possible_keys: NULL
          key: name_index
      key_len: 152
          ref: NULL
         rows: 10
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.00 sec)

上面的例子中, 我們查詢的 name 字段恰好是一個索引, 因此我們直接從索引中獲取數據就可以滿足查詢的需求了, 而不需要查詢表中的數據. 因此這樣的情況下, type 的值是 index, 並且 Extra 的值是 Using index.

  • ALL: 表示全表掃描, 這個類型的查詢是性能最差的查詢之一. 通常來說, 我們的查詢不應該出現 ALL 類型的查詢, 因爲這樣的查詢在數據量大的情況下, 對數據庫的性能是巨大的災難. 如一個查詢是 ALL 類型查詢, 那麼一般來說可以對相應的字段添加索引來避免.

下面是一個全表掃描的例子, 可以看到, 在全表掃描時, possible_keys 和 key 字段都是 NULL, 表示沒有使用到索引, 並且 rows 十分巨大, 因此整個查詢效率是十分低下的.

mysql> EXPLAIN SELECT age FROM  customer WHERE age = 20 \G*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: customer
   partitions: NULL
         type: ALL
possible_keys: NULL
          key: NULL
      key_len: NULL
          ref: NULL
         rows: 10
     filtered: 10.00
        Extra: Using where
1 row in set, 1 warning (0.00 sec)

type 類型的性能比較

通常來說, 不同的 type 類型的性能關係如下:ALL < index < range ~ index_merge < ref < eq_ref < const < system

ALL 類型因爲是全表掃描, 因此在相同的查詢條件下, 它是速度最慢的.而 index 類型的查詢雖然不是全表掃描, 但是它掃描了所有的索引, 因此比 ALL 類型的稍快.後面的幾種類型都是利用了索引來查詢數據, 因此可以過濾部分或大部分數據, 因此查詢效率就比較高了.

對程序員來說,若保證查詢至少達到range級別或者最好能達到ref則算是一個優秀而又負責的程序員。

  • ALL:(full table scan)全表掃描無疑是最差,若是百萬千萬級數據量,全表掃描會非常慢。
  • index:(full index scan)全索引文件掃描比all好很多,畢竟從索引樹中找數據,比從全表中找數據要快。
  • range:只檢索給定範圍的行,使用索引來匹配行。範圍縮小了,當然比全表掃描和全索引文件掃描要快。sql語句中一般會有between,in,>,< 等查詢。
  • ref:非唯一性索引掃描,本質上也是一種索引訪問,返回所有匹配某個單獨值的行。比如查詢公司所有屬於研發團隊的同事,匹配的結果是多個並非唯一值。
  • eq_ref:唯一性索引掃描,對於每個索引鍵,表中有一條記錄與之匹配。比如查詢公司的CEO,匹配的結果只可能是一條記錄,
  • const:表示通過索引一次就可以找到,const用於比較primary key 或者unique索引。因爲只匹配一行數據,所以很快,若將主鍵至於where列表中,MySQL就能將該查詢轉換爲一個常量。
  • system:表只有一條記錄(等於系統表),這是const類型的特列,平時不會出現,瞭解即可

possible_key

spossible_keys 表示 MySQL 在查詢時, 能夠使用到的索引. 注意, 即使有些索引在 possible_keys 中出現, 但是並不表示此索引會真正地被 MySQL 使用到. MySQL 在查詢時具體使用了哪些索引, 由 key 字段決定.

key

此字段是 MySQL 在當前查詢時所真正使用到的索引.

key_len

表示查詢優化器使用了索引的字節數. 這個字段可以評估組合索引是否完全被使用, 或只有最左部分字段被使用到.
key_len 的計算規則如下:

  • 字符串
    char(n): n 字節長度
    varchar(n): 如果是 utf8 編碼, 則是 3 n + 2字節;
    如果是 utf8mb4 編碼, 則是 4 n + 2 字節.

  • 數值類型:
    TINYINT: 1字節
    SMALLINT: 2字節
    MEDIUMINT: 3字節
    INT: 4字節
    BIGINT: 8字節

  • 時間類型
    DATE: 3字節
    TIMESTAMP: 4字節
    DATETIME: 8字節

  • 字段屬性: NULL 屬性 佔用一個字節. 如果一個字段是 NOT NULL 的, 則沒有此屬性.
    我們來舉兩個簡單的栗子:

mysql> EXPLAIN SELECT * FROM order_info WHERE user_id < 3 AND product_name = 'p1' AND productor = 'WHH' \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: order_info
   partitions: NULL
         type: range
possible_keys: user_product_detail_index
          key: user_product_detail_index
      key_len: 9
          ref: NULL
         rows: 5
     filtered: 11.11
        Extra: Using where; Using index
1 row in set, 1 warning (0.00 sec)


上面的例子是從表 order_info 中查詢指定的內容, 而我們從此表的建表語句中可以知道, 表 order_info 有一個聯合索引:

KEY `user_product_detail_index` (`user_id`, `product_name`, `productor`)

不過此查詢語句 WHERE user_id < 3 AND product_name = ‘p1’ AND productor = ‘WHH’ 中, 因爲先進行 user_id 的範圍查詢, 而根據 最左前綴匹配 原則, 當遇到範圍查詢時, 就停止索引的匹配, 因此實際上我們使用到的索引的字段只有 user_id, 因此在 EXPLAIN 中, 顯示的 key_len 爲 9. 因爲 user_id 字段是 BIGINT, 佔用 8 字節, 而 NULL 屬性佔用一個字節, 因此總共是 9 個字節. 若我們將user_id 字段改爲 BIGINT(20) NOT NULL DEFAULT ‘0’, 則 key_length 應該是8.

上面因爲 最左前綴匹配 原則, 我們的查詢僅僅使用到了聯合索引的 user_id 字段, 因此效率不算高.

接下來我們來看一下下一個例子:

mysql> EXPLAIN SELECT * FROM order_info WHERE user_id = 1 AND product_name = 'p1' \G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: order_info
   partitions: NULL
         type: ref
possible_keys: user_product_detail_index
          key: user_product_detail_index
      key_len: 161
          ref: const,const
         rows: 2
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.00 sec)

這次的查詢中, 我們沒有使用到範圍查詢, key_len 的值爲 161. 爲什麼呢? 因爲我們的查詢條件 WHERE user_id = 1 AND product_name = ‘p1’ 中, 僅僅使用到了聯合索引中的前兩個字段, 因此 keyLen(user_id) + keyLen(product_name) = 9 + 50 * 3 + 2 = 161

rows

rows 也是一個重要的字段. MySQL 查詢優化器根據統計信息, 估算 SQL 要查找到結果集需要掃描讀取的數據行數.

這個值非常直觀顯示 SQL 的效率好壞, 原則上 rows 越少越好.

Extra

EXplain 中的很多額外的信息會在 Extra 字段顯示, 常見的有以下幾種內容:

Using filesort當 Extra 中有 Using filesort 時, 表示 MySQL 需額外的排序操作, 不能通過索引順序達到排序效果. 一般有 Using filesort, 都建議優化去掉, 因爲這樣的查詢 CPU 資源消耗大.例如下面的例子:

mysql> EXPLAIN SELECT * FROM order_info ORDER BY product_name \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: order_info
   partitions: NULL
         type: index
possible_keys: NULL
          key: user_product_detail_index
      key_len: 253
          ref: NULL
         rows: 9
     filtered: 100.00
        Extra: Using index; Using filesort
1 row in set, 1 warning (0.00 sec)

我們的索引是

KEY `user_product_detail_index` (`user_id`, `product_name`, `productor`)

但是上面的查詢中根據 product_name 來排序, 因此不能使用索引進行優化, 進而會產生 Using filesort.

如果我們將排序依據改爲 ORDER BY user_id, product_name, 那麼就不會出現 Using filesort 了. 例如:

mysql> EXPLAIN SELECT * FROM order_info ORDER BY user_id, product_name \G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: order_info
   partitions: NULL
         type: index
possible_keys: NULL
          key: user_product_detail_index
      key_len: 253
          ref: NULL
         rows: 9
     filtered: 100.00
        Extra: Using index
1 row in set, 1 warning (0.00 sec)

Using index

“覆蓋索引掃描”, 表示查詢在索引樹中就可查找所需數據, 不用掃描表數據文件, 往往說明性能不錯

Using temporary

查詢有使用臨時表, 一般出現於排序, 分組和多表 join 的情況, 查詢效率不高, 建議優化.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章