Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Khác biệt giữa SHOW INDEX, SHOW INDEXES và SHOW KEYS trong MySQL

Giới thiệu

Ba câu lệnh SHOW INDEX, SHOW INDEXES, SHOW KEYS hoàn toàn tương đương nhau trong MySQL. Chúng đều hiển thị thông tin chỉ mục của bảng.

1. Tạo bảng và chỉ mục

mysql> create table DemoTable1549 (
    -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
    -> EmployeeName varchar(20)
    -> ); 
Query OK, 0 rows affected (0.82 sec)

mysql> create index name_index1 on DemoTable1549(EmployeeName); 
Query OK, 0 rows affected (0.41 sec)
Records: 0 Duplicates: 0 Warnings: 0

2. SHOW INDEX

mysql> show index from DemoTable1549;
+---------------+------------+-------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| Table         | Non_unique | Key_name    | Seq_in_index | Column_name  | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible |
+---------------+------------+-------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| demotable1549 |          0 | PRIMARY     |            1 | EmployeeId   | A         |           0 |     NULL | NULL   |      | BTREE      |         |               | YES     |
| demotable1549 |          1 | name_index1 |            1 | EmployeeName | A         |           0 |     NULL | NULL   | YES  | BTREE      |         |               | YES     |
+---------------+------------+-------------+--------------+--------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
2 rows in set (0.17 sec)

3. SHOW INDEXES

mysql> show indexes from DemoTable1549;

Kết quả y hệt SHOW INDEX.

4. SHOW KEYS

mysql> show keys from DemoTable1549;

Kết quả y hệt (có thể hiển thị hơi khác về khoảng trắng/cột NULL).

Kết luận: Ba lệnh này là alias của nhau. MySQL chấp nhận cả ba để tương thích. Thường dùng SHOW INDEX hoặc SHOW KEYS.

Các cột quan trọng:

  • Non_unique: 0 = duy nhất (PRIMARY/UNIQUE), 1 = không duy nhất
  • Key_name: Tên chỉ mục (PRIMARY cho khóa chính)
  • Seq_in_index: Thứ tự cột trong chỉ mục tổng hợp
  • Cardinality: Số giá trị duy nhất ước lượng (để optimizer quyết định dùng index)
  • Index_type: BTREE, HASH, FULLTEXT, SPATIAL
  • Visible: YES/NO (từ MySQL 8.0, ẩn index khỏi optimizer)