Note/数据库导论/试题/综合案例5——索引.md

4.7 KiB
Raw Blame History

综合案例5——索引

本部分介绍了什么是索引以及索引的种类及各种索引的创建方法如建表的同时创建索引、使用alter table或create index语句创建索引。索引是提高数据库性能的一个强有力的工具因此同学们要掌握好索引的创建。

1、案例目的

创建数据库index_test按照下面表结构在index_test数据库中创建两个数据表test_table1和test_table2如表1表2所示并按照操作过程完成对数据表的基本操作。

表1 test_table1表结构

字段名 数据类型 主键 外键 非空 唯一 自增
id int11
name char100
address char100
description char100

表2 test_table2表结构

字段名 数据类型 主键 外键 非空 唯一 自增
id int11
firstname char50
middlename char50
lastname char50
birth date
title char100

2、案例操作过程

1登录MySQL数据库。

mysql -u root -p

截图:

2创建数据库index_test并选择使用此数据库。

create database index_test;
use index_test;

截图:

image-20220407094114402

3按照表1创建test_table1表并在建表的同时创建如下索引在id上创建名称为UniqIdxid的唯一索引在name(长度20),address(长度30)上创建名称为MultiColIdx的组合索引在description(长度30)上创建名称为ComIdx的普通索引。

create table test_table1(
id int (11) not null unique auto_increment,
name char(100) not null,
address char(100),
description char(100),
unique index UniqIdx(id),
index MultiColIdx(name(20),address(30)),
index ComIdx(description(30))
);

截图:

image-20220407101245380

4使用show语句查看索引信息。

show index from test_table1;

截图:

image-20220407101300158

5按照表2创建表test_table2存储引擎为MyISAM。

create table test_table2(
id int(11) not null unique,
firstname char(50) not null,
middlename char(50) not null,
lastname char(50) not null,
birth date not null,
title char(100),
primary key(id)
)engine=MyISAM;

截图:

image-20220407100253683

6使用alter table语句在test_table2的birth字段上建立名称为ComDateIdx的普通索引

alter table test_table2 add index ComDateIdx(birth);

截图:

image-20220407100726287

7使用alter table语句在test_table2的id字段上添加名称为UniqIdx2的唯一索引并以降序排列。

alter table test_table2 add unique index UniqIdx2(id);

截图:

image-20220407100738304

8使用create index在firstname、middlename和lastname 3个字段上建立名称为MultiColIdx2的组合索引。

create index MultiColIdx2 on test_table2(firstname,middlename,lastname);

截图:

image-20220407100905384

9使用create index在title字段上建立名称为FTIdx的全文索引

create fulltext index FTIdx on test_table2(title);

截图:

image-20220407101003860

10使用alter table语句删除表test_table1中名称为UniqIdx的唯一索引。

alter table test_table1 drop index UniqIdx;

截图:

image-20220407101326523

11使用drop index语句删除表test_table2中名称为MultiColIdx2的组合索引。

drop index MultiColIdx2 on test_table2;

截图:

image-20220407101408468