在 MySQL 中使用 EXPLAIN 關鍵字


MySQL EXPLAIN 提供查詢執行計劃。可以在 SELECT、INSERT、DELETE、REPLACE 和 UPDATE 開頭使用 EXPLAIN。

為了避免資料庫中全表掃描,需要使用索引。我們首先建立一個表 −

mysql> create table DemoTable1488
   -> (
   -> StudentId int,
   -> StudentName varchar(20),
   -> StudentAge int
   -> );
Query OK, 0 rows affected (2.18 sec)

以下是建立索引的查詢 −

mysql> create index student_id_index on DemoTable1488(StudentId);
Query OK, 0 rows affected (0.90 sec)
Records: 0  Duplicates: 0  Warnings: 0

使用 insert 命令向表中插入一些記錄-插入一些記錄 −

mysql> insert into DemoTable1488 values(101,'Sam',21);
Query OK, 1 row affected (0.32 sec)
mysql> insert into DemoTable1488 values(102,'Bob',23);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable1488 values(103,'David',20);
Query OK, 1 row affected (0.21 sec)

使用 select 語句從表中顯示所有記錄 −

mysql> select * from DemoTable1488;

這將產生以下輸出 −

+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
|       101 | Sam         |         21 |
|       102 | Bob         |         23 |
|       103 | David       |         20 |
+-----------+-------------+------------+
3 rows in set (0.00 sec)

現在,使用 EXPLAIN −

mysql> explain select * from DemoTable1488 where StudentId=1;

這將產生以下輸出 −

+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
| id | select_type | table         | partitions | type | possible_keys    | key              | key_len  | ref | rows  | filtered | Extra |
+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | DemoTable1488 | NULL       | ref  | student_id_index | student_id_index | 5       | const |    1 | 100.00   | NULL |
+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

更新於:11-Dec-2019

322 閱讀量

開啟你的 職業生涯

完成課程認證

開始
廣告