1. 索引的引入
索引定义:索引是由数据库表中一列或者多列组合而成,其作用是
提高对表中数据的查询速度;类似于图书的目录,方便快速定位,
寻找指定的内容。
2. 索引的优缺点
优点:提高查询数据的速度:
缺点:创建和维护索引的时间增加了;
3. 索引的实例
4.索引的分类
1. 普通索引
这类索引可以创建在任何数据类型中;
2. 唯一性索引
使用UNION参数可以设置,在创建唯一性索引时,可以限制该索引的值
必须是唯一的。
3. 全文索引
使用FULLTEXT参数可以设置,全文索引只能创建在CHAR,VARCHAR,
TEXT类型的字段上。主要作用就是提高查询较大字符串类型的速度;
只有MySAM引擎支持该索引,Mysql默认下引擎不支持;
4. 单列索引
在表中可以给单个字段创建索引,单列索引可以是普通索引,也可以是
唯一性索引,还可以是全文索引。
5. 多列索引
多列索引是在表的多个字段上创建一个索引;
6. 空间索引
使用SPATIAL参数可以设置空间索引。空间索引只能建立在空间数据类型上,
这样可以提高系统获取空间数据的效率;
5.创建索引
5.1创建表的时候创建索引
CREATE TABLE 表名 (属性名 数据类型 【完整性约束条件】,
属性名 数据类型 【完整性约束条件】,
.......
属性名 数据类型
【UNIQUE|FULLTEXT|SPATIAL|INDEX|KEY】
【别名】(属性名1 【(长度)】【ASC|DESC】)
);
1.创建普通索引
create table user1(id int,
userName varchar(20) ,
password varchar(20),
index index_userName(userName)
);
2.创建唯一性索引
create table user1(id int,
userName varchar(20) ,
password varchar(20),
unique index index_userName(userName)
);
3.创建全文索引
4.创建单列索引
5.创建多列索引
create table user3(id int,
userName varchar(20),
password varchar(20),
index index_userName_password(userName, password)
);
6.创建空间索引
5.2,在已经存在的表上创建索引
CREATE【UNIQUE|FULLTEXT|SPATIAL】INDEX索引名
ON 表名 (属性名【(长度)】【ASC|DESC】);
例子:
create index index_password on user2(password);
create unique index index_password on user2(password);
create index index_userName_password on user2(userName
, password);
5.3.用ALTER TABLE语句来创建索引
ALTER TABLE 表名 ADD【UNIQUE|FULLTEXT|SPATIAL】INDEX索引名
ON 表名 (属性名【(长度)】【ASC|DESC】);
例子:
alter table user1 add index index_userName(userName);
alter table user1 add unique index index_userName(userName);
alter table user1 add index index_userName_password(userName
, password);
6.删除索引
DROP INDEX 索引名 ON 表名;
例子:
drop index index_userName on user1;