Mysql索引分类

一、单值索引

概念:即一个索引只包含单个列,一个表可以有多个单列索引

语法:

1.随表一起创建

create table customer (
id int(10) unsigned auto_increment,
customer_no varchar(200),
customer_name varchar(200),
primary key(id),
key (customer_name)
);

2.单独建单值索引

create index idx_customer_name on customer(customer_name);

二、唯一索引

概念:索引列的值必须唯一,但允许有空值

1.随表一起创建

create table customer (
id int(10) unsigned auto_increment,
customer_no varchar(200),
customer_name varchar(200),
primary key(id),
key (customer_name),
unique (customer_no)
);

2.单独建唯一索引

create unique index idx_customer_no on customer(customer_no);

三、主键索引

概念:设定为主键后数据库会自动建立索引,innodb为聚簇索引

1.随表一起建索引

create table customer (
id int(10) unsigned auto_increment,
customer_no varchar(200),
customer_name varchar(200),
primary key(id)
);

2.单独建主键索引

alter table customer add primary key customer(customer_no);

3.删除建主键索引

alter table customer drop primary key ;

4.修改建主键索引

必须先删除掉(drop)原索引,再新建(add)索引

四、复合索引

概念:即一个索引包含多个列

1.随表一起建索引

create table customer (
id int(10) unsigned auto_increment,
customer_no varchar(200),
customer_name varchar(200),
primary key(id),
key (customer_name),
unique (customer_name),
key (customer_no,customer_name)
);

2.单独建索引

create index idx_no_name on customer(customer_no,customer_name);

五、基本语法

操作命令
创建

create [unique] index[indexName] on table_name(column)

alter table_name add [unique] index [indexName] on (column);

删除drop index[indexName] on table_name
查看show index from table_name\G
使用alter命令

alter table tbl_name add primary key(column_list):该语句添加一个主键,这意味着索引值必须是唯一的,且不能为null。

alter table tbl_name add unique index_name(column_list):这条语句创建索引的值必须是唯一的(除了null外,null可能会出现多次)

alter table tbl_name add index index_name(column_list):添加普通索引,索引值可以出现多次。

alter table tbl_name add fulltext index_name(column_list):该语句指定了索引为fulltext,用于全文索引。

六、索引的创建时机

6.1 适合创建索引的情况

1.主键自动建立唯一索引;

2.频繁作为查询条件的字段应该创建索引;

3.查询中与其它表关联的字段,外键关系建立索引

4.单价/组合索引的选择问题,组合索引性价比更高

5.查询中排序的字段,排序字段若通过索引去访问将大大提高排序速度;

6.查询中统计或者分组字段

6.2 不适合创建索引的情况

1.表记录太少;

2.经常增删改的表或者字段;

3.where条件里用不到的字段不创建索引

4.过滤性不好的不适合建索引。

5.如果某个数据列包含众多重复的内容,为它建立索引,没有太大的实际效果。

参考博客视频教程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值