码迷,mamicode.com
首页 > 数据库 > 详细

MySQL-索引

时间:2018-09-14 17:15:46      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:51cto   varchar   字段   har   创建表   长度   查看   shadow   rom   

一、MySQL索引介绍

索引是一种数据结构,以其特有的记录数据的方式,为用户提供高性能的查询。索引就像是一本新华字典的目录,通过目录可以快速的找到我们想要找到的数据。

二、MySQL主要使用的索引

普通索引:MySQL中基本索引类型,仅有加速查询功能,允许在定义索引的列中插入重复的值和空值。
主键索引:有两个功能:加速查询 和 唯一约束(不可含null)
唯一索引:有两个功能:加速查询 和 唯一约束(可含null)
组合索引:组合索引是将n个列组合成一个索引

三、普通索引

1、创建索引

part1:创建表时创建索引
create table user(
    nid int not null auto_increment primary key,
    name varchar(50) not null,
    passwd varchar(100) not null,
    extra text,
    index idx1(name)
)![](http://i2.51cto.com/images/blog/201809/14/39334e56fbb24560becb2c8a0ae9cc98.png?x-oss-process=image/watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=)

note:如果是CHAR,VARCHAR类型,length可以小于字段实际长度;如果是BLOB和TEXT类型,必须指定 length。

part2:创建索引
create index idx2 on user(name);

2、查看索引

show index from user;

3、删除索引

drop index idx2 on user;

四、唯一索引

1、创建索引

part1:创建表时创建索引
create table user(
    nid int not null auto_increment primary key,
    name varchar(50) not null,
    passwd varchar(100) not null,
    extra text,
    unique idx1(name)
)
part2:创建索引
create unique idx2 on user(name);

2、查看索引

show index from user;

3、删除索引

drop index idx2 on user;

五、主键索引

1、创建主键索引

part1:创建表时创建索引
create table user(
    nid int not null auto_increment ,
    name varchar(50) not null,
    passwd varchar(100) not null,
    extra text,
    primary key(nid),
    index idx1(name)
)

part2:创建索引

alter table idx2 add primary key(nid);

2、删除主键

alter table user drop primary key;
alter table user modify  nid int, drop primary key;

六、组合索引

1、创建组合索引

part1:创建表时创建索引
create table user(
    nid int not null auto_increment primary key,
    name varchar(50) not null,
    passwd varchar(100) not null,
    index idx(nid,name,passwd)
)
part2:创建索引
create index idx on user(nid,name,passwd);

2、查看索引

show index from user;

3、删除索引

drop index idx on user;

组合索引查询遵循最左匹配:如查询:
nid and name :使用索引
nid and passwd :使用索引
passwd:不适用索引

七、覆盖索引

上述4种MySQL常用的索引,其查找数据的顺序都是先在索引中找,再去数据表中找。如果一个查询只在索引中便能完成,而不需要去数据表中找,这种索引被称为覆盖索引。覆盖索引必须要求存储索引的列,所以只有btree索引能使用更为高效的覆盖索引。

查看覆盖索引(Using index)

技术分享图片

MySQL-索引

标签:51cto   varchar   字段   har   创建表   长度   查看   shadow   rom   

原文地址:http://blog.51cto.com/jiayimeng/2175280

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!