美文网首页
MySQL - 索引

MySQL - 索引

作者: 番薯IT | 来源:发表于2017-10-26 15:28 被阅读26次

索引的类型

主键索引

  • 创建表的时候指定主键
-- 创建表
create table t_user(
    id varchar(32) not null,
    nickname varchar(20) not null,
    age tinyint not null default 0,
    gender tinyint not null default 2,
    birthday date not null default ‘1997-01-01’,
    id_card char(18) not null default '',
    remark varchar(512) not null default '',
    primary key(id)
);

-- 查看t_user表中的索引
show index in t_user;
  • 在创建完表之后指定
-- 创建没有指定主键的表
create table t_demo(id varchar(32) not null, name varchar(20) not null);
-- 设置主键
alter table t_demo add primary key(id);
-- 查看
show index in t_demo;

唯一索引

唯一索引的命名一般以uniq作为前缀,下划线风格。

alter table t_user add unique uniq_nickname(nickname);

show index in t_user;

普通索引

普通索引的命名一般以idx作为前缀,下划线风格。

alter table t_user add index idx_age(age);

组合索引

-- 创建身份证号、出生年月、性别的组合索引
alter table t_user add index idx_idcard_birth_gender(id_card, birthday, gender);

全文索引

MyISam才支持全文索引

alter table t_user add fulltext index idx_remark(remark);

索引未命中场景

  • 有隐式转换
explain select * from t_user where mobile = 15333333333;

mobile是varchar类型的,但是查询并没有带单引号(''),会导致索引未命中,正确应该如下:

explain select * from t_user where mobile = '15333333333';
  • 有负向查询
# 主键id上的操作
explain select * from t_user where id = 1;
explain select * from t_user where id <> 1;
# 在属性age上的操作
explain select * from t_user where age = 23;
explain select * from t_user where age != 23;

执行完之后,我们可以发现主键id上的负向查询用到了索引,不过执行计划中的typerange
在age上的负向查询就没有命中索引。

  • 有前导模糊查询
explain select * from t_user where mobile like '%185';

从执行计划中我们能看到,索引没有命中,是全表扫描的。
但是下面这样的插叙是能命中索引的:

explain select * from t_user where mobile like '185%';
  • 查询条件字段上有计算
explain select * from t_user where age - 1 = 22;
explain select * from t_user where pow(age, 2) = 200;
explain select * from t_user where mobile = concat(mobile, 'm');

上面的是不能命中索引的


参考

相关文章

  • MySQL索引及查询优化书目录

    MySQL索引的原理之索引目的 MySQL索引的原理之索引原理 MySQL索引的原理之索引的类型 MySQL索引的...

  • 高性能的索引策略

    MySQL查询基础-查询执行过程 MySQL聚簇索引 MySQL覆盖索引 MySQL索引扫描排序 MySQL冗余和...

  • MySQL索引的使用

    MySQL索引 MySQL索引可以快速提高MySQL的检索速度。索引分单列索引和组合索引单列索引:即一个索引只包含...

  • Mysql索引与锁

    本文以Mysql5.7为例测试。 1:mysql索引方法 Mysql的索引方法分为btree索引和hash索引。 ...

  • 索引(二)

    mysql索引的新手入门详解mysql索引之三:索引使用注意规则 索引(Index)是帮助 MySQL 高效获取数...

  • MySQL 索引分类

    MySQL索引的分类(根据数据结构) 索引的本质 MySQL官方对索引的定义为:索引(Index)是帮助MySQL...

  • MySQL--索引

    MySQL索引 查看索引 创建索引 创建唯一索引 创建主键索引 删除索引 删除主键 MySQL视图 创建视图 删除...

  • mysql索引

    索引 mysql索引的建立对于mysql的高效运行是很重要的,索引可以大大提高mysql的检索速度。索引分单列索引...

  • 5.2MySQL创建高性能索引考察点

    MySQL索引的基础和类型延伸:MySQL索引的创建原则延伸:MySQL索引的注意事项 索引的基础索引类似于书籍的...

  • MySql 数据查询优化

    1. MySQL索引类型: mysql的索引有5种:主键索引、普通索引、唯一索引、全文索引、聚合索引(多列索引)。...

网友评论

      本文标题:MySQL - 索引

      本文链接:https://www.haomeiwen.com/subject/szfzjxtx.html