3.1 问题
具体要求如下:
在已有表里添加index字段
建表时,添加index字段
查看表索引
删除表索引
3.2 步骤
实现此案例需要按照如下步骤进行。
步骤一:索引的创建与删除
1)创建表的时候指定INDEX索引字段
创建库home:
mysql> create database home;
Query OK, 1 row affected (0.00 sec)
允许有多个INDEX索引字段。比如,以下操作在home库中创建了tea4表,将其中的id、name作为索引字段:
mysql> USE home;
Database changed
mysql> CREATE TABLE tea4(
-> id char(6) NOT NULL,
-> name varchar(6) NOT NULL,
-> age int(3) NOT NULL,
-> gender ENUM('boy','girl') DEFAULT 'boy',
-> INDEX(id),INDEX(name)
-> );
Query OK, 0 rows affected (0.59 sec)
查看新建tea4表的字段结构,可以发现两个非空索引字段的KEY标志为MUL:
mysql> DESC tea4;
+--------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------------+------+-----+---------+-------+
| id | char(6) | NO | MUL | NULL | |
| name | varchar(6) | NO | MUL | NULL | |
| age | int(3) | NO | | NULL | |
| gender | enum('boy','girl') | YES | | boy | |
+--------+--------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
2)删除现有表的某个INDEX索引字段
比如,删除tea4表中名称为named的INDEX索引字段:
mysql> drop INDEX name ON tea4; //删除name字段的索引
Query OK, 0 rows affected (0.18 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> DESC tea4; //确认删除结果
+--------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------------+------+-----+---------+-------+
| id | char(6) | NO | MUL | NULL | |
| name | varchar(6) | NO | | NULL | |
| age | int(3) | NO | | NULL | |
| gender | enum('boy','girl') | YES | | boy | |
+--------+--------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
3)在已有的某个表中设置INDEX索引字段
比如,针对tea4表的age字段建立索引,名称为 nianling:
mysql> CREATE INDEX nianling ON tea4(age); //针对指定字段创建索引
Query OK, 0 rows affected (0.62 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> DESC tea4; //确认创建结果
+--------+--------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+--------+--------------------+------+-----+---------+-------+
| id | char(6) | NO | MUL | NULL | |
| name | varchar(6) | NO | | NULL | |
| age | int(3) | NO | MUL | NULL | |
| gender | enum('boy','girl') | YES | | boy | |
+--------+--------------------+------+-----+---------+-------+
4 rows in set (0.00 sec)
4)查看指定表的索引信息
使用SHOW INDEX 指令:
mysql> SHOW INDEX FROM tea4\G
*************************** 1. row ***************************
Table: tea4
Non_unique: 1
Key_name: id
Seq_in_index: 1
Column_name: id
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE //使用B树算法
Comment:
Index_comment:
*************************** 2. row ***************************
Table: tea4
Non_unique: 1
Key_name: nianling //索引名称
Seq_in_index: 1
Column_name: age //字段名称
Collation: A
Cardinality: 0
Sub_part: NULL
Packed: NULL
Null:
Index_type: BTREE
Comment:
Index_comment:
2 rows in set (0.00 sec)
Query OK, 0 rows affected (0.30 sec)
Mysql>
Query OK, 0 rows affected (0.47 sec)
Records: 0 Duplicates: 0 Warnings: 0