作者:学Java的冬瓜
博客主页:☀冬瓜的主页
专栏:【MySQL】
分享:纵一苇之所如,凌万顷之茫然。——《赤壁赋》
主要内容:MySQL中索引的介绍、创建索引、使用索引;索引背后的数据结构的分析、关于二叉搜索树、AVL树、B树、B+树这些数据结构分析
可以对表中的一列或者多列创建索引,各类索引有各自的数据结构实现。
原理:当查询某一项时,使用索引后,查询不是从原表中查所有数据再显示目标项,而是将索引拿来查询,数据量大大减少,从而提高查询效率。
优点:
缺点:
前提:我创建了一个student表,id为主键,还有一个name字段
mysql> desc student;
+-------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id | int | NO | PRI | NULL | |
| name | varchar(20) | YES | | NULL | |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)
创建表时,有主键/unique/外键,都会自动创建索引
-- 查看索引
show index from 表名
mysql> show index from student;
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| student | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | | | YES | NULL |
+---------+------------+----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
1 row in set (0.04 sec)
对于一个非主键,非唯一约束,非外键约束的字段,可以采用普通索引
-- 创建索引
create index 索引名 on 表名(字段名)
mysql> create index ind_name_stu on student(name);
Query OK, 0 rows affected (0.06 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> show index from student;--可以看到,多出了关于name的索引
+---------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+---------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| student | 0 | PRIMARY | 1 | id | A | 0 | NULL | NULL | | BTREE | | | YES | NULL |
| student | 1 | ind_name_stu | 1 | name | A | 0 | NULL | NULL | YES | BTREE | | | YES | NULL |
+---------+------------+--------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
2 rows in set (0.04 sec)
-- 删除索引
drop index 索引名 on 表名
哈希表:
二叉搜索树(BST=>Binary Search Tree):
N叉搜索树(B树=>Binary Tree):
B+树: