索引简介

索引分类

索引指令

显示表中所有的索引

SQL
show index from `表名`;

索引的创建

创建表时

SQL
create table `表名`(
    字段。。。
    primary key (`字段`),
    unique key `索引名`(`字段名`),
    key `索引名` (`字段名`),
    fullText key `索引名` (`字段名`)
)engine=INNODB charset=utf8;

添加表级别索引约束

SQL
alter table `表名` add unique key `索引名` (`字段名`);
alter table `表名` add key `索引名` (`字段名`);
alter table `表名` add fulltext key `索引名` (`字段名`);
SQL
create 类型 index 索引名 on `表名`(`字段`);

分析explain

作用:分析select查询语句使用情况。

SQL
explain select 查询语句;

组合索引

SQL
create table `student`(
    `id` int(11) not null  auto_increment,
    `name` varchar(20) not null,
    `address` varchar(20) not null,
    ....

    primary key (`id`,`name`),
    key `索引名`(`name`,`address`),
    unique `索引名` (`address`,`id`)
)engine=INNODB charset=utf8;

索引原则

[!note|style:flat]

  1. 索引不是越多越好
  2. 不需要对经常变动的数据添加索引
  3. 小数据不需要索引
  4. 索引添加到需要经常查询的字段上
  5. 索引优先级:主键索引,单列索引,组合索引

License

Author: 海拉鲁的三角

Link: http://localhost:1313/cpp_notes/posts/mysql/indexs/

License: MIT

只要学不死,就往死里学