索引用于快速找出在某个列中有一特定值的行,不使用索引,MySQL必须从第一条记录开始读完整个表,直到找出相关的行,表越大,查询数据所花费的时间就越多,如果表中查询的列有一个索引,MySQL能够快速到达一个位置去搜索数据文件,而不必查看所有数据,那么将会节省很大一部分时间。
例如,我们要找一本书的某个内容,如果没有索引,我们就需要从头开始翻,一直翻到最后一页,这会大大浪费我们的时间,而有了索引就会大大节省了我们的时间。
当我们给某一字段添加主键时,系统会自动为这一字段创建索引。因为InnoDB的数据文件本身按主键聚集,所以InnoDB要求表必须有主键(MyISAM可以没有),如果没有显示指定,则MySQL系统会自动选择一个可以唯一标识数据记录的列作为主键,如果不存在这种列,则MySQL自动为InnoDB表生成一个隐含字段作为主键,这个字段长度为6个字节,类型为长整型。
查看一张表的索引
用法:
show index from 表名;
show index from students;
建立索引
用法:
普通索引
create index 索引名 on table_name(字段名); #为那张表的那个字段建立索引。
create index index_name on students(姓名,身份证号码);
唯一索引
create unique index index_name on table_name(字段名);
全文索引
create fulltext index index_name on table_name(字段名);
多列索引
create index index_name on table_name(字段1,字段2…);
也可以在创建表时直接创建索引
create table school(
name varchar(8) not null,
sid int primary key auto_increment not null,
age int not null,
sex enum('F','M'),
index(sid,name)
);
在已存在的表上添加索引
alter table school add index index_name(name);
删除索引
drop index index_name on table;
#table是表名
索引测试实验
explain select * from t1 where id>50000;
create index index_id on t1(id);
将通配符写在最左边 (他不会命中索引表,因为他是匹配任意字符,还是会搜索表的所有内容)
create index index22 on students(姓名,身份证号码);
explain select 姓名 from students where 姓名 like '%张%';
explain select 姓名 from students where 姓名 like '张%';
最左原则(他会按照你建立的索引的最左边的字段来搜索,如果没有匹配到最左边的,就算你为另一个字段建立了索引,他也不会来搜索,也无法匹配到)
create index index22 on students(姓名,就业薪资);
explain select 姓名 from students where 就业薪资>12000;