索引
一种数据结构,(B树或者是哈希结构),提高查询效率。
索引是创建在数据库表中,是对数据库表中的一列或者多列值进行排序的一个结果,好处就是提高查询效率。
- 索引的分类:
-
普通索引:没有任何限制,可以给任何字段创建普通索引;
-
唯一性索引:使用Unique修饰的 字段,值不能重复,主键索引就是唯一性索引;
-
主键索引:使用primary key修饰的字段自动创建主键索引,不能为空;
-
外键索引:可以为空;
-
单列索引:一个字段上创建索引;
-
多列索引:在多个字段上创建索引;
-
全文索引:使用fullText参数可以设置全文索引,只支持char、varchar、text类型的字段上,常用于数据量较大的字符串类型上;
-
联合索引:将两个索引关键字连在一起,加快查询效率。
- 索引的创建和删除SQL命令:
- 索引的创建:
(1)在创建表的时候指定索引字段:
create table tablename(id int,name varchra(10),index(id));
(2)在已经创建的表上添加索引:
create (unique/fulltext/spaptial) index idx_id(索引名) on 表名(字段名id);
eg: create index idx_name on Student(Sname);
alter table tablename add (unique/fulltext/spaptial) index index_name (字段名id);
(3)在已创建的表上设置联合索引:
alter table table_name add index index_name(id , name);//创建(id,name)的联合索引;
注意:过滤条件where = XX,index(XX在前面);
直接就去id辅助索引树上就可以直接查询到name;
- 删除索引:
(1)drop index index_name on 表名;
索引执行过程分析:explain select 语句
explain select * from Student where Sid = 1/g;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: Student
partitions: NULL
type: const
possible_keys: PRIMARY
key: PRIMARY
key_len: 4
ref: const
rows: 1
filtered: 100.00
Extra: NULL
1 row in set, 1 warning (0.00 sec)
mysql> explain select * from Student where Sage = 20\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: Student
partitions: NULL
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 5
filtered: 20.00
Extra: Using where
1 row in set, 1 warning (0.00 sec)
当前查询的possible_keys,key都为null,则未命中索引,
rows=5:表示当前查询操作对每一行数据都进行比较,遍历了;
//增加索引后
alter table Student add index idx_sage(Sage);
//分析执行过程
mysql> explain select * from Student where Sage = 20\G;
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: Student
partitions: NULL
type: ref
possible_keys: idx_sage
key: idx_sage
key_len: 4
ref: const
rows: 2
filtered: 100.00
Extra: NULL
1 row in set, 1 warning (0.04 sec)
当前查询命中idx_sage,rows:2,表示通过两条记录查询到了结果,Sage=20 的有两个人
possible keys:表示SQL执行过程可能会命中的索引有哪些;
key :表示执行过程真正使用的索引名称;
key_len:
rows:表示查询影响的数据行数;