👨🎓 博主介绍:
IT邦德,江湖人称jeames007,10年DBA工作经验
中国DBA联盟(ACDU)成员,目前从事DBA及程序编程
文章目录
1.索引的创建
1.1. 普通索引
create table if not exists tb_student1 (
studentNo CHAR(10) not NULL primary key comment '学号',
studentName VARCHAR(10) NOT null comment '姓名',
sex CHAR(2) comment '性别',
birthday date comment '出生日期',
native VARCHAR(20) comment '籍贯',
nation VARCHAR(10) DEFAULT '汉' comment '民族',
classNo CHAR(6) comment '所属班级',
INDEX idx_studentName(studentName)
) ENGINE=InnoDB comment '学生表';
注:INDEX idx_studentName(studentName)这个是关键
此方法是创建新表的同时创建普通索引
1.2. 唯一索引
CREATE TABLE tb_class1 (
classNo CHAR(6) PRIMARY KEY NOT NULL,
className VARCHAR(20) NOT NULL,
department VARCHAR(20),
grade ENUM('1','2','3','4'),
classNum TINYINT,
constraint uq_class unique(className),
UNIQUE INDEX uqidx_className(className)
) engine=InnoDB default charset=gb2312;
注: UNIQUE INDEX uqidx_className(className)是关键
此方法是创建新表时创建唯一索引
1.3. 主键索引
CREATE TABLE tb_course1 (
courseNo CHAR(6) primary key comment '课程号',
courseName VARCHAR(20) unique not NULL comment '课程名',
credit DECIMAL(3,1) not NULL comment '学分',
courseHour TINYINT(2) not NULL comment '课时数',
term TINYINT(2) comment '开课学期',
priorCourse CHAR(6) comment '先修课程'
) engine=InnoDB default charset=gb2312;
注: courseNo CHAR(6) primary key comment '课程号' 是关键
次方法是在创建新表的同时创建主键索引
1.4. 升序降序索引
CREATE TABLE tb_score1(
studentNo CHAR(10) NOT NULL comment '学号',
courseNo CHAR(6) NOT NULL comment '课程号',
credit DECIMAL(4,1) not NULL comment '成绩'
) engine=InnoDB default charset=gb2312;
alter table tb_score1 add index idx_studentNo(studentNo desc);
alter table tb_score1 add index idx_courseNo(courseNo);
2.索引的维护
2.1 查看索引
2.2 删除普通索引
2.3 删除主键索引
3.技能拓展
3.1 索引介绍
基于InnoDB,数据结构都是B+树,特点是:
主键索引存储的是Mysql整个数据行
普通索引存储的是索引列和主键的值
Mysql 8.0.13版本及以上已经出现了函数索引
3.2 索引的创建原则
a.出现Where子句中的列(比较频繁)
b.索引的基数越大的越好(唯一值)
c.短索引(列的长度)
d.排序 order by 、分组 group by (适合建索引)
e.数据量少的做索引