数据库学习4

来源:互联网 发布:ubuntu 启动器 图标 编辑:程序博客网 时间:2024/06/07 23:39

刘江    11511010019

叶公正 11511010024

 创建索引
1. 创建表时创建索引
基本形式:

create table 表名(
属性名 数据类型 [完整性约束条件],
属性名 数据类型 [完整性约束条件]
...
[unique|fulltext|spatial] index|key [别名](属性名1 [(长度)] [asc|desc])
)
示例:

create table index1(id int,name varchar(5),index(id));
2. 在已经存在表中创建索引
基本形式:

create [unique|fulltext|spatial] index 索引名 on 表名 (属性名 [(长度)] [asc|desc]);
单字段索引
create index c2_idx on student(sno);
show index from su;
explain select * from su a,(select c2 from su where id=10) b where a.c2=b.c2;
多字段索引(联合索引) 最左前缀原则
create index idx_c3_c4 on su(c3,c4);
show index from su;
explain select * from su where c3=21;
explain select * from su where c4=21;
explain select * from su where c3=21 order by c4;
explain select * from su where c4=21 order by c3;
只能使用一个索引

explain select * from su where c3=21 or c4=21;
总结,尽量少用联合索引。

create index c3_index on su(c3);
create index c4_index on su(c4);
explain select * from su where c3=21 or c4=21;
explain select * from su where c3=21 union all select * from su where c4=21;
** union all既不排序、也不去重;union排序、去重 **

前缀索引
create index name_idx on table_name(name(6));
3. 用alter table语句创建索引
基本形式:

alter table 表名 add [unique|fulltext|spatial] index 索引名 (属性名 [(长度)] [asc|desc]);
示例:

alter table tb add index index_name(id);
删除索引
alter table 表名 drop index 索引名;
drop index 索引名 on 表名;
alter table su drop index idex_c3_

原创粉丝点击