概念:即一个索引只包含单个列,一个表可以有多个单列索引
语法:
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.如果某个数据列包含众多重复的内容,为它建立索引,没有太大的实际效果。
参考博客,视频教程