MySQL中的索引类型有:
- 普通索引(
index
或key
):可以取空值或重复值。 - 唯一性索引(
unique
):索引列值不能重复。 - 主键索引(
primary key
):主键索引时一种唯一性索引,不同在于,其索引列值不能为空。 - 聚簇索引 :索引顺序就是数据存储的物理存储顺序,一个表只能有一个聚簇索引,目前仅支持solidDB和InnoDB存储引擎。
- 非聚簇索引:索引顺序与数据的物理排列顺序无关。
- 全文索引(
fulltext
):只能创建在数据类型为varchar
或text
的列上,仅支持MyISAM存储引擎。
查看索引
show index丨keys from丨in tb_score;
创建索引
表不存在create table
--普通索引
create table tb_student
( studentNo char(10) not null,
studentName varchar(20) not null,
index(studentName));
--唯一性索引、主键索引、外键索引的创建方式与创建约束的方式相同,当创建约束时,系统会自动创建相应索引。
约束的创建方法请移步《计算机二级MySQL学习笔记(第三章)》。
表已存在create index
/ alter table
--创建基于 courseName 字段值前三个字符的降序索引,索引名称为 index_course
create index index_course on tb_course(courseName(3) desc);
--创建 tb_book 表中图书类别(bclassNo 升序)和书名(bookName 降序)的组合索引,索引名为 index_book
create index index_book on tb_book (bclassNo,bookName desc);
--使用 alter table 添加索引
alter table tb_student add index idx_studentName(studentName);
这里create index
/ alter table
的创建索引类型是有限制的,详情请移步官方手册MySQL官方手册。
删除索引
drop index
语句
drop index index_name on table_name;
alter table
语句
alter table table_name drop index index_name;
课后习题
1、在tb_student表上创建主键索引
--创建主键约束后,自动创建主键索引
alter tb_student add constraint PK_studentNo primary key(studentNo);
这里我认为题目有问题,create index 语句的官方手册里是不能创建主键索引的,只能创建unique\fulltext\spatial索引,官方手册请移步 create index语法。
2、建立学号、课程号的组合索引
create table tb_score
( studentNo char(10) not null,
courseNo char(10) not null,
constraint index_score index(studentNo,courseNo);
)
3、删除索引
drop index index_score on tb_score;
或
alter table tb_score drop index index_score;