• MySQLStudy——索引



    索引:

    作用: 加快查询的速度

    类比: 新华字典的目录, 可以将索引理解成一个特殊的文件, 然后如果没有这个文件的话, 查询是从前到后查找数据的,
    如果有这个文件的话, 会按照一种特殊的数据结构(二叉树)查找数据

    分类:
    主键索引: 加快查询 + 不能重复 + 不能为空 primary key
    唯一索引: 加快查询 + 不能重复 unique(列名)
    联合唯一索引: 加快查询 + 不能重复 unique(列名1,列名2)
    普通索引: 加快查询 index('列名')


    创建:

    主键索引:
    第一种:
    create table t1(
    id int auto_increment primary key,
    name varchar(32) not null default ''
    )engine=Innodb charset=utf8;
    第二种:
    alter table t1 change id id int auto_increment primary key;

    唯一索引:

    第一种:
    create table t1(
    id int auto_increment primary key,
    name varchar(32) not null default '',
    unique ix_name ('name')
    )engine=Innodb charset=utf8;

    第二种:
    create unique index 索引名称(ix_name) on 表名(t1)(name);
    create unique index 索引名称(ix_name_age) on 表名(t1)(name,age);

    普通索引:
    索引名字不需要加单引号

    第一种:
    create table t1(
    id int auto_increment primary key,
    name varchar(32) not null default '',
    index ix_name (name)
    )engine=Innodb charset=utf8;

    第二种:
    create index 索引名称(ix_name) on 表名(t1)(name);

    删除:
    drop 索引名称(ix_name) on 表名(t1);

    场景:
    使用频繁的列上加一个索引

    索引的缺点:

    版本5.3以下:
    删除和修改的速度就变慢了

    版本5.5以上:
    删除和修改的速度不是特别的慢

    create table t12(
    id int auto_increment primary key,
    name varchar(32) not null default '',
    email varchar(32) not null default ''
    )engine=Innodb charset=utf8;


    索引的使用:

    explain 工具

    查看sql语句是否用的上索引, 或者查看sql执行效率的工具

    给执行的SQL语句出一个报告, 通过此报告来判断sql语句的执行效率和效果

    ES (elasticsearch )
    SQL语句的规则:

    - 不建议使用 like 进行搜索
    - 组合索引最左前缀
    如果组合索引为:(name,email)
    where name and email -- 使用索引
    where name -- 使用索引
    where email -- 不使用索引

  • 相关阅读:
    设置zookeeper开机自启动
    安装zookeeper
    Elasticsearch 5.6.5 安装head插件
    [redis] Node is not empty. Either the node already knows other nodes
    【redis】 redis 创建集群时,Waiting for the cluster to join.... 一直等待
    [redis] redis.clients.jedis.exceptions.JedisDataException: MOVED 13102 127.0.0.1
    [linux] FastDFS访问文件,400 Bad Request
    [linux] Nginx编译安装错误error: the HTTP rewrite module requires the PCRE library
    [java] java解析txt文件
    【java】 java 解压tar.gz读取内容
  • 原文地址:https://www.cnblogs.com/tingguoguoyo/p/11042590.html
Copyright © 2020-2023  润新知