MYSQL-索引

1. 索引基本操作

1.1 查询表中的所有索引

show index from 表名;

1.2 删除表中索引

#方式一:
drop index 索引名 on 表名;
#方式二:
alter table 表名 drop index 索引名;

2. 创建索引

2.1 创建普通索引

方式一:在建表时创建普通索引

#给id列建立索引,索引名最好为index_字段名
create table student (
id int,
name varchar(10),
index index_id(id)
);

方式二:给已有表添加普通索引

#给已有表建立索引
create index 索引名 on 表名(字段)
eg: create index index_id on student(id);

alter table 表名 add index 索引名(字段)
eg: alter table student add index index_id(id);

2.2 创建唯一索引

方式一:在建表时创建唯一索引

#给id列建立索引,索引名最好为index_字段名
create table student (
id int,
name varchar(10),
unique index_id(id)
);

 方式二:给已有表添加唯一索引

create unique index 索引名 on 表名(字段);
eg: create unique index index_id on student(id);

alter table 表名 add unique index 索引名(字段);
alter table student add unique index index_id(id);

2.3 创建组合索引

方式一:在建表时创建组合索引

#给id和name列建立索引,索引名最好为index_字段名_字段名
create table student (
id int,
name varchar(10),
index index_id_name(id,name)
);

 方式二:给已有表添加组合索引

create index 索引名 on 表名(字段1,字段2);
create index index_id_name on student(id,name);

alter table 表名 add index 索引名(字段1,字段2);
alter table student add index index_id_name(id,name);

注:在组合索引中where条件的第一个索引字段不存在时,即使有第二个索引字段也不生效;

例如:

select * from student where name='小花';
#此时的index_id_name索引不生效

select * from student where id=1;
#此时的index_id_name索引生效

select * from student where id=1 and name='小花';
#此时的index_id_name索引生效

select * from student where name='小花' and id=1;
#此时的index_id_name索引生效
  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值