优点
1.创建唯一索引,可以保证数据库表中每行数据的唯一性
2.可以大大加快数据的查询速度,这也是创建索引最主要的原因
缺点:
1.创建索引和维护索引需要耗费时间,并且随着数据量的增加耗费的时间也会增加
2.索引需要占用磁盘空间,除了数据表占数据空间之外,每个索引还要占用一定的物理空间
索引可以分为以下几类:
1.普通索引和唯一索引
2.单列索引和组合索引
3.全文索引
4.空间索引
一、索引的设计原则:
1.索引并不是越多越好,一个表中有大量的索引会降低update、insert、delete等语句的性能,因为当表中的数据进行更改时,索 引 也会调整和更新。
2.避免对经常更新的表创建过多的索引,并且索引中的列尽可能少,对于查询的字段可以创建索引
3.数据量小的表不要使用索引,查询数据的时间比查询索引的时间还要短,索引可能不会产生优化效果
4.在平凡进行分组和排序(group by或order by操作)的列上创建索引
二、索引的使用
1.建表时创建索引
--1.创建普通索引
create table USER(
id int not null AUTO_INCREMENT,
username varchar(20),
age INT,
sex char(1),
phone varchar(11),
PRIMARY KEY(id),
INDEX(phone)
)
--2.创建唯一索引
--创建唯一索引主要是为了减少查询索引列操作的执行时间
CREATE table user2(
id int NOT null AUTO_INCREMENT,
username varchar(20),
PRIMARY key (id),
UNIQUE index u_id(id)
)
3.创建单列唯一索引
create table user4(
id int not null AUTO_INCREMENT,
username varchar(20),
phone varchar(11),
PRIMARY key (id),
unique index s_phone (phone)
)
--4.创建组合唯一索引
CREATE TABLE USER3(
id int not null AUTO_INCREMENT,
username varchar(20),
phone varchar(11),
PRIMARY key (id),
UNIQUE key s_phone (phone,username)
)
--5创建全文索引
CREATE TABLE USER5(
id int not null AUTO_INCREMENT,
username varchar(20),
phone varchar(11),
PRIMARY key (id),
FULLTEXT INDEX f_username (username)
)
2.在已经存在的表上创建索引
CREATE index 索引名称 ON 表名 (指定列添加索引)
CREATE index s_phone ON user11 (phone)
CREATE UNIQUE index s_phone ON user11 (phone)
3.删除索引
--删除索引
方法1
ALTER TABLE 表名 DROP index 索引名称
ALTER TABLE user11 DROP index s_phone
方法2
DROP index 索引名称 on 表名
DROP index s_phone on user11