zoukankan      html  css  js  c++  java
  • mysql联合索引详解

    联合索引又叫复合索引。对于复合索引:Mysql从左到右的使用索引中的字段,一个查询可以只使用索引中的一部份,但只能是最左侧部分。例如索引是key index (a,b,c)。 可以支持a | a,b| a,b,c 3种组合进行查找,但不支持 b,c进行查找 .当最左侧字段是常量引用时,索引就十分有效。

        两个或更多个列上的索引被称作复合索引。

        利用索引中的附加列,您可以缩小搜索的范围,但使用一个具有两列的索引 不同于使用两个单独的索引。复合索引的结构与电话簿类似,人名由姓和名构成,电话簿首先按姓氏对进行排序,然后按名字对有相同姓氏的人进行排序。如果您知 道姓,电话簿将非常有用;如果您知道姓和名,电话簿则更为有用,但如果您只知道名不姓,电话簿将没有用处。

        所以说创建复合索引时,应该仔细考虑列的顺序。对索引中的所有列执行搜索或仅对前几列执行搜索时,复合索引非常有用;仅对后面的任意列执行搜索时,复合索引则没有用处。

        如:建立 姓名、年龄、性别的复合索引。

        create table test(

        a int,

        b int,

        c int,

        KEY a(a,b,c)

        );

        优: select * from test where a=10 and b>50

        差: select * from test where a50

        优: select * from test order by a

        差: select * from test order by b

        差: select * from test order by c

        优: select * from test where a=10 order by a

        优: select * from test where a=10 order by b

        差: select * from test where a=10 order by c

        优: select * from test where a>10 order by a

        差: select * from test where a>10 order by b

        差: select * from test where a>10 order by c

        优: select * from test where a=10 and b=10 order by a

        优: select * from test where a=10 and b=10 order by b

        优: select * from test where a=10 and b=10 order by c

        优: select * from test where a=10 and b=10 order by a

        优: select * from test where a=10 and b>10 order by b

        差: select * from test where a=10 and b>10 order by c

       索引原则

        1.索引越少越好

        原因:主要在修改数据时,每个索引都要进行更新,降低写速度。

        2.最窄的字段放在键的左边

        3.避免file sort排序,临时表和表扫描。

        4.MySQL能在多个列上创建索引。一个索引可以由最多15个列组成。(在CHAR和VARCHAR列上,你也可以使用列的前缀作为一个索引的部分)。

    注意:

    一:

    对于CHAR和VARCHAR列,你可以索引列的前缀。这更快并且比索引整个列需要较少的磁盘空间。在CREATE TABLE语句中索引列前缀的语法看起来像这样:

    KEY index_name (col_name(length))
    下面的例子为name列的头10个字符创建一个索引:

    mysql> CREATE TABLE test (
    name CHAR(200) NOT NULL,
    KEY index_name (name(10)));

    对于BLOB和TEXT列,你必须索引列的前缀,你不能索引列的全部。

    二:

    聚集索引

    一种索引,该索引中键值的逻辑顺序决定了表中相应行的物理顺序。 聚集索引确定表中数据的物理顺序。Mysqlmyisam表是没有聚集索引的,innodb有(主键就是聚集索引),聚集索引在下面介绍innodb结构的时有详细介绍。

    参考:

    由浅入深探究mysql索引结构原理、性能分析与优化

    http://blog.csdn.net/turkeyzhou/article/details/8182636

  • 相关阅读:
    windows常用命令行总结
    express安装
    MySQL去除外键关联关系
    c#实体转化
    C#之Clone
    mysql 将null转代为0(转)
    Mysql显示行号
    mysql存储过程游标加计划任务事件调度器
    mysql临时表
    Git学习笔记
  • 原文地址:https://www.cnblogs.com/Alight/p/3713579.html
Copyright © 2011-2022 走看看