mysql(索引)

一、索引

B-tree

功能:约束、加速查询

约束(主键、外键、唯一、普通、组合)

索引的缺点:增删改查等修改数据时速度减慢,增加存储,创建索引耗费资源会有锁表的风险

索引种类:

1、普通索引(加速查询)

2、唯一索引(加速查询 和 唯一约束(可以为null))
3、主键索引((加速查询 和 唯一约束(不可以为null)))
4、组合索引(联合唯一,多列可以创建一个索引文件,加速查询 和 唯一约束(不可以为null))

创建索引:

1、普通索引

1)创建表 + 索引
create table in1(
nid int not null auto_increment primary key,
name varchar(32) not null,
email varchar(64) not null,
extra text,
index ix_name (name)
)

2)插入索引——在已有数据库中创建索引
create index index_name on table_name(column_name)

3)删除索引

drop index_name on table_name;
4)查看索引

show index from table_name;

2、唯一索引

1)创建表 + 唯一索引
create table in1(
nid int not null auto_increment primary key,
name varchar(32) not null,
email varchar(64) not null,
extra text,
unique ix_name (name)
)

2)插入索引——在已有数据库中创建索引
create unique index 索引名 on 表名(列名)

3)删除索引
drop unique index 索引名 on 表名

3、主键索引

1)创建表 + 唯一索引

create table in1(
nid int not null auto_increment primary key,
name varchar(32) not null,
email varchar(64) not null,
extra text,
index ix_name (name)
)

OR

create table in1(
nid int not null auto_increment,
name varchar(32) not null,
email varchar(64) not null,
extra text,
primary key(nid),
index ix_name (name)
)

2)添加主键

alter table 表名 add primary key(列名);

3)删除主键
alter table 表名 drop primary key;

4)更新主键
alter table 表名 modify 列名 int, drop primary key;

4、组合索引

1)普通组合索引:
无约束
2)联合唯一索引:
有约束,两列数据同时不相同,才能插入,不然报错
注:查找:最左匹配
select * from tb1 where name = 'zk'
select * from tb1 where name = 'zk'and pwd = '666'
select * from tb1 where pwd = '666' #不会走索引

 

http://www.cnblogs.com/wupeiqi/articles/5713323.html

猜你喜欢

转载自www.cnblogs.com/arctis-zk/p/10394847.html