何时应在 MySQL 中使用复合索引?

mysqlmysqli database

使用子查询时可以使用复合索引。使用复合索引的优点如下。

  • 连接
  • 过滤
  • 选择

以下是索引的语法。

index(column_name1,column_name2,column_name3,column_name4,............................N)

让我们先创建一个表,然后在其中设置索引。

mysql> create table MultipleIndexDemo
   - > (
   - > id int,
   - > FirstName varchar(100),
   - > LastName varchar(100),
   - > Address varchar(200),
   - > index(id,LastName,Address)
   - > );
Query OK, 0 rows affected (0.57 sec)

检查索引是否创建成功。

mysql> show index from MultipleIndexDemo;

以下是输出。

+-------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| Table             | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible |
+-------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
| multipleindexdemo |          1 | id       |            1 | id          | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     |
| multipleindexdemo |          1 | id       |            2 | LastName    | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     |
| multipleindexdemo |          1 | id       |            3 | Address     | A         |           0 |     NULL |   NULL | YES  | BTREE      |         |               | YES     |
+-------------------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+
3 rows in set (0.18 sec)

相关文章