zoukankan      html  css  js  c++  java
  • MySQL 索引

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

    一. 普通索引

    作用:加速查找

    # 1.创建表时直接创建索引
    create table user(
        nid int not null auto_increment primary key,
        name varchar(32) not null,
        email varchar(64) not null,
        extra text,
        index ix_name (name)        # ix_name 索引名,括号后面指定索引所在的列
    );
    
    # 2.创建表后再创建索引
    create index ix_name on user(name);
    #注意:对于创建索引时如果是BLOB 和 TEXT 类型,必须指定length,例如使用列名称的前10个字符:
    create index ix_extra on user(extra(10));
    
    # 3.删除索引
    drop ix_name on user;
    
    # 4.查看索引
    show index from user;
    

    二. 唯一索引

    作用:加速查找,约束列数据不能重复,数据可以为 null

    # 1.创建表时直接创建唯一索引
    create table user(
        nid int not null auto_increment primary key,
        name varchar(32) not null,
        email varchar(64) not null,
        extra text,
        unique ix_name (name)        
    );
    
    # 2.创建表后再创建唯一索引
    create  unique index ix_name on user(name);
    
    # 3.删除唯一索引
    drop unique ix_name on user;
    

    三. 主键索引

    作用:加速查找,约束列数据不能重复,数据不能为 null

    # 1.创建表时直接创建主键索引
    create table user(
        nid int not null auto_increment primary key,    # 指定 nid 为主键索引
        name varchar(32) not null,
        email varchar(64) not null,
        extra text      
    );
    
    # 2.创建表后添加主键索引
    alter table user add primary key(nid);
    
    # 3.删除主键索引
    alter table user drop primary key;
    

    四. 组合索引

    作用:多列可以创建一个索引文件

    # 1.创建组合索引
    create table user(
        nid int not null auto_increment primary key,   
        name varchar(32) not null,
        email varchar(64) not null,
        extra text      
    );
    
    # 将 name 和 email 两列组合成一个索引
    create index ix_name_email on user(name,email);
    
    # 组合索引遵循最左前缀,即 where条件必须跟 name 列才会使用索引。
    

    覆盖索引

    只需要在索引表中就能获取到数据。

    合并索引

    # 有两个单独的索引,搜索时使用两个索引
    create table user(
        nid int not null auto_increment primary key,
        name varchar(32) not null,
        email varchar(64) not null,
        extra text,
        index ix_name(name) ,
        index ix_email(email)
    );
    
    select * from user where name = 'klvchen' or email = 'klvchen@126.com'; 
    

    使用索引注意事项

    • 避免使用select *
    • count(1)或count(列) 代替 count(*)
    • 创建表时尽量时 char 代替 varchar
    • 表的字段顺序固定长度的字段优先
    • 组合索引代替多个单列索引(经常使用多个条件查询时)
    • 尽量使用短索引
    • 使用连接(JOIN)来代替子查询(Sub-Queries)
    • 连表时注意条件类型需一致
    • 索引散列值(重复少)不适合建索引,例:性别不适合
  • 相关阅读:
    一个C++的unit库
    一篇关于如何组织unit tests的文章,很有趣
    web开发者的checklist
    用了story point就一定agile了吗?
    C#中如何用Windows Management Instrumentation (WMI)得到系统信息
    Windows下C++的同步机制的演变
    Sysinternals自动更新的工具SyncTools
    什么情况下要替换C++自带的new和delete
    VS2012插件:可视化TFS代码版本历史
    Quattro发布自助手机广告产品
  • 原文地址:https://www.cnblogs.com/klvchen/p/10135904.html
Copyright © 2011-2022 走看看