2.4 索引语法
1). 创建索引
代码语言:javascript复制CREATE [ UNIQUE | FULLTEXT ] INDEX index_name ON table_name (
index_col_name,... ) ;
2). 查看索引
代码语言:javascript复制SHOW INDEX FROM table_name ;
3). 删除索引
代码语言:javascript复制DROP INDEX index_name ON table_name ;
案例演示:
先来创建一张表 tb_user,并且查询测试数据。
代码语言:javascript复制create table tb_user(
id int primary key auto_increment comment '主键',
name varchar(50) not null comment '用户名',
phone varchar(11) not null comment '手机号',
email varchar(100) comment '邮箱',
profession varchar(11) comment '专业',
age tinyint unsigned comment '年龄',
gender char(1) comment '性别 , 1: 男, 2: 女',
status char(1) comment '状态',
createtime datetime comment '创建时间'
) comment '系统用户表';
INSERT INTO tb_user (name, phone, email, profession, age, gender, status,
createtime) VALUES ('吕布', '17799990000', 'lvbu666@163.com', '软件工程', 23, '1',
'6', '2001-02-02 00:00:00');
INSERT INTO tb_user (name, phone, email, profession, age, gender, status,
createtime) VALUES ('曹操', '17799990001', 'caocao666@qq.com', '通讯工程', 33,
'1', '0', '2001-03-05 00:00:00');
INSERT INTO tb_user (name, phone, email, profession, age, gender, status,
createtime) VALUES ('赵云', '17799990002', '17799990@139.com', '英语', 34, '1',
'2', '2002-03-02 00:00:00');
INSERT INTO tb_user (name, phone, email, profession, age, gender, status,
createtime) VALUES ('孙悟空', '17799990003', '17799990@sina.com', '工程造价', 54,
'1', '0', '2001-07-02 00:00:00');
INSERT INTO tb_user (name, phone, email, profession, age, gender, status,
createtime) VALUES ('花木兰', '17799990004', '19980729@sina.com', '软件工程', 23,
'2', '1', '2001-04-22 00:00:00');
INSERT INTO tb_user (name, phone, email, profession, age, gender, status,
createtime) VALUES ('大乔', '17799990005', 'daqiao666@sina.com', '舞蹈', 22, '2',
'0', '2001-02-07 00:00:00');
INSERT INTO tb_user (name, phone, email, profession, age, gender, status,
createtime) VALUES ('露娜', '17799990006', 'luna_love@sina.com', '应用数学', 24,
'2', '0', '2001-02-08 00:00:00');
表结构中插入的数据如下:
数据准备好了之后,接下来,我们就来完成如下需求:
A. name字段为姓名字段,该字段的值可能会重复,为该字段创建索引。
代码语言:javascript复制CREATE INDEX idx_user_name ON tb_user(name);
B. phone手机号字段的值,是非空,且唯一的,为该字段创建唯一索引。
代码语言:javascript复制 CREATE UNIQUE INDEX idx_user_phone ON tb_user(phone);
C. 为profession、age、status创建联合索引。
代码语言:javascript复制CREATE INDEX idx_user_pro_age_sta ON tb_user(profession,age,status);
D. 为email建立合适的索引来提升查询效率。
代码语言:javascript复制CREATE INDEX idx_email ON tb_user(email);
完成上述的需求之后,我们再查看tb_user表的所有的索引数据。
代码语言:javascript复制show index from tb_user;