索引解决的问题:提高查询速度
一.单列索引
1.普通索引
注意:自动创建索引的约束类型 主键 唯一 外键
(1)普通索引的创建
方法一:在表中创建索引
语法:index 索引名字 (列名);
eg:index index_name(name);
方式二:直接创建
语法:create index 索引名字 on 表名(列名);
eg:create index index_gender on student(gender);
方式三:修改表结构(添加索引)
语法:alter table 表名 add index 索引名 (列名);
eg:alter table student add index index_age(age);
(2)查看索引
1.查看数据库所有索引
语法:select * from mysql. `innodb index stats` a where a.`database name数据库名';
eg:select * from mysql.`innodb index stats`a where a.`database name’= 'cat';
2.查看表中所有索引
语法:select * from mysql.`innodb index stats` a where a.`database name`='数据库名'and a.table name like'%表名%';
eg:select * from mysql.`innodb index stats`a where a.`database name’= 'mydb5'and a.table name like '%student%';
注意:1和2在低版本的MySQL无效,低版本的MySQL对3生效
3.设置索引的可见性
语法:alter table 表名 alter 索引名 invisible;
eg:alter table t alter index idx_b invisible;
4.查看表中所有索引
语法:show index from table name;
eg:show index from student;
5.简单的执行计划
在查询的前面加explain
explain select ename from emp where empno = 7369;
(3)删除索引
语法:①drop index 索引名 on 表名
②alter table 表名 drop index 索引名
注:二选一
eg:①drop index index gender on student;
②alter table student drop index index name;
2.唯一索引
(1)唯一索引的创建
1.创建表的时候直接指定
语法:unique 索引名(列名)
eg:unique index_card_id(card_id)
2.直接创建
语法:create unigue 索引名 on 表名(列名)
eg:create unique index index card id on student2(card id);
3.修改表结构(添加索引)
语法:alter table 表名 add unique 索引名 (列名)
eg:alter table student2 add unique index phone num(phone num)