Computer >> Máy Tính >  >> Lập trình >> MySQL

Sử dụng từ khóa EXPLAIN trong MySQL

MySQL EXPLAIN đưa ra một kế hoạch thực thi truy vấn. EXPLAIN có thể được sử dụng ngay từ đầu với SELECT, INSERT, DELETE, REPLACE và UPDATE.

Để tránh quét toàn bộ bảng trong cơ sở dữ liệu, bạn cần sử dụng chỉ mục. Đầu tiên chúng ta hãy tạo một bảng -

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

Đây là truy vấn để tạo chỉ mục -

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

chèn vào giá trị DemoTable1488 Chèn một số bản ghi trong bảng bằng lệnh 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)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select * from DemoTable1488;

Điều này sẽ tạo ra kết quả sau -

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

Bây giờ, hãy sử dụng EXPLAIN -

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

Điều này sẽ tạo ra kết quả sau -

+----+-------------+---------------+------------+------+------------------+------------------+---------+-------+------+----------+-------+
| 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)