• Mysql 复合键索引性能


         数据库的常见的索引一般是单个字段,如果多个字段的组合,那么就组成了复合索引。对于组合索引,如果

    对其中一字段做为条件查询,会出现什么情况呢?

    一、例子

    mysql> show create table watchdogG
    *************************** 1. row ***************************
       Table: watchdog
       Create Table: CREATE TABLE `watchdog` (
           `index1` int(11) NOT NULL DEFAULT '0',
           `index2` int(11) NOT NULL DEFAULT '0',
           `dog` int(11) NOT NULL DEFAULT '9',
            PRIMARY KEY (`index1`,`index2`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    
        1 row in set (0.00 sec)

    创建了以上数据表,索引是复合索引(index1, index2),针对以两种情况:

    <1>
    select index1, index2 
    from watchdog 
    where index1 > 4000008 and index1 < 4200007; 
    <2>
    select index1, index2 
    from watchdog 
    where index2 > 4000009 and index2 < 4200007;

    诚然,大多数人可能认为这两个情况索引都是一样的,至少我自己这么认为。

    二、验证

    对以上的两情况实验结果

    <1>
     ...
    | 4200001 | 4200002 |
    | 4200002 | 4200003 |
    | 4200003 | 4200004 |
    | 4200004 | 4200005 |
    | 4200005 | 4200006 |
    | 4200006 | 4200007 |
    +---------+---------+
    
    199997 rows in set (0.09 sec)
    <2>
    ...
    | 4200002 | 4200003 |
    | 4200003 | 4200004 |
    | 4200004 | 4200005 |
    | 4200005 | 4200006 |
    +---------+---------+
    
    199997 rows in set (1.68 sec)

    两种情况的性能消耗时间相距甚远。其原因为何?

    三、结果

    查明原因,MySQL的复制索引在Where条件下有三种情形:

    <1>没有用到复合索引

    <2>只用到第一个索引

    <3>用到全部的索引

    所以,针对以上实验第二情况所使用到的第二个索引,起不了索引作用。

    文档:

    http://stackoverflow.com/questions/26255039/mysql-column-order-in-composite-key/26255121

    http://dev.mysql.com/doc/refman/5.7/en/multiple-column-indexes.html

    Note: explain命令虽可以解析sql语句,但具体还是要再斟酌一下。

  • 相关阅读:
    Python-Re正则表达式库
    杂记
    Python 信息提取-beautifulsoup实例
    Python 中国大学排名定向爬虫
    matlab-汉字unicode编码转换
    Python-beautifulsoup库
    python 安装resquest
    python--数字灯管
    Python time库
    Python random库
  • 原文地址:https://www.cnblogs.com/zhuangzebo/p/4018065.html
Copyright © 2020-2023  润新知