一、什么是索引
可以把索引理解为一种特殊的目录,能加快数据库的查询速度,它也是一类文件,占用一定的物理空间,
确切说,索引是对数据库表中一列或者多列的值进行排序的一种结构,使用索引可以快速定位到特定值,
mysql常用的索引结构有:b+tree和hash两种,
二、索引的分类及相关操作
1、普通索引index,可以重复,可以为null,可以一列或多列,一个表中可以有多个,
-- 1、创建索引——新建表中 create table student ( nid int not null auto_increment, name char not null, sex tinyint not null default 0, index stu_num(nid) ); -- 2、创建索引——现有表中 create index stu_name on student(name); -- 3、删除索引 drop index stu_name on student; -- 4、查看索引 show index from student;
2、唯一索引:不可以重复,可以为null(但仅允许有一个null),可以一列或者多列,一个表中可以有多个,
-- 1、创建索引——新建表中 create table student1 ( nid int not null auto_increment, name char not null, sex tinyint not null default 0, unique stu_num(nid) ); -- 2、创建索引——现有表中 create unique index stu_name on student1(name); -- 3、删除索引 drop index stu_name on student1; -- 4、查看索引 show index from student1;
3、主键索引:不可以重复,不可以为null,可以一列或者多列,一个表中仅有一个,表中的自增列通常设为主键,
-- 1、创建主键——新建表中 create table student ( nid int not null auto_increment, name char not null, sex tinyint not null default 0, primary key (nid,name) ); -- 2、创建主键——现有表中 alter table student add primary key(nid); -- 3、删除主键 alter table student drop primary key; -- 4、查看主键 show index from student;
4、全文索引:定义一个词库,把每个分词出现的频率和位置信息,按照词库的顺序归纳,相当于建立了一个以词库为目录的索引,
三、其他
(一)查看表中的索引设置
1、show index from 表名;显示表中所有设置索引的列,
2、desc 表名;显示表中所有列及各列的配置信息,
(二)查看sql使用的索引方式
explain + select……;显示全部检索相关的具体信息, 此为执行计划,
(三)查看检索占用的具体时间
set profiling=1;……sql……;show profiles;

浙公网安备 33010602011771号