1.什么是索引
汉语字典中的汉字按页存放,一般都有汉语拼音目录(索引)、偏旁部首目录等。
我们可以根据拼音或偏旁部首,快速查找某个字词。
Indexes Use Key Values to Locate Data (根据索引键查找定位数据行)
索引是一种有效组合数据的方式,为快速查找到指定记录。
作用
大大提高数据库的检索速度
改善数据库性能
MySQL索引按存储类型分类
B-树索引:InnoDB、MyISAM均支持
哈希索引
2.常见索引类型
2.1普通索引
基本索引类型
允许在定义索引的列中插入重复值和空值
唯一索引
索引列数据不重复
允许有空值,创建唯一约束时自动创建唯一索引
主键索引
主键列中的每个值是非空、唯一的
一个主键将自动创建主键索引
复合索引
将多个列组合作为索引
全文索引
支持值的全文查找
允许重复值和空值
空间索引
对空间数据类型的列建立的索引
3.管理索引
使用SQL语句创建索引
语法
CREATE [UNIQUE|FULLTEXT|SPATIAL] INDEX index_name
ON table_name (column_name[length]…);
使用SQL语句删除视图
DROP INDEX index_name ON table_name;
示例
#student表的studentName列创建普通索引
CREATE INDEX `index_student_studentname` ON `student`(`studentname`);
4.创建索引的指导原则
按照下列标准选择建立索引的列
频繁搜索的列
经常用作查询选择的列
经常排序、分组的列
经常用作连接的列(主键/外键)
请不要使用下面的列创建索引
仅包含几个不同值的列
表中仅包含几行
优化SQL语句的意识
查询时减少使用*返回全部列,不要返回不需要的列;
索引应该尽量小,在字节数小的列上建立索引;
WHERE子句中有多个条件表达式时,包含索引列的表达式应置于其他条件表达式之前;
避免在ORDER BY子句中使用表达式。
根据业务数据发生频率,定期重新生成或重新组织索引,进行碎片整理。
5.MySQL的备份
数据库备份必要性
保证重要数据不丢失
数据转移
MySQL数据库备份方法
数据库管理工具,如SQLyog
mysqldump备份工具
直接拷贝数据库文件和相关配置文件
MySQL的恢复
MySQL数据库恢复方法
数据库管理工具,如SQLyog
mysql命令
语法
mysql –u root –p dbname < /path/db_name.sql;
本节的笔记
CREATE INDEX INDEX_NAME ON STUDENT(STUDENTNAME)
drop index INDEX_NAME ON STUDENT
EXPLAIN select * from student;
EXPLAIN select studentname,sex from student;
EXPLAIN select studentname from student;
EXPLAIN select * from student where studentname = '孙尚香';
EXPLAIN select * from student where studentno = 1007;
EXPLAIN select * from student where studentname = '孙尚香' and studentno = 1009;
EXPLAIN select * from student where studentname like '张%';
-- 模糊查询时,左全匹配时会导致索引失效
EXPLAIN select * from student where studentname like '%飞';
EXPLAIN select * from student where studentname like '%张%';
CREATE INDEX INDEX_NAME ON STUDENT(STUDENTNAME,address,email)
-- 复合索引必须按照最左原则,否则会失效
EXPLAIN select * from student where studentname = '张飞';
EXPLAIN select * from student where studentname = '张飞' and address='安徽庐江';
EXPLAIN select * from student where studentname = '张飞' and address='安徽庐江' and email='18555555555@163.com';
EXPLAIN select * from student where address='安徽庐江';
EXPLAIN select * from student where email='18555555555@163.com';
EXPLAIN select * from student where address='安徽庐江' and email='18555555555@163.com';
EXPLAIN select * from student where address='安徽庐江' and studentname = '张飞';
EXPLAIN select * from student where address='安徽庐江' and email='18555555555@163.com' and studentname = '张飞';
-- 查询姓张的学生
EXPLAIN select * from student where studentname like '张%';
-- 查询条件包含索引列时,一定不要对索引列做函数处理,否则会导致索引失效
EXPLAIN select * from student where SUBSTR(studentname,1,1) = '张';