zoukankan      html  css  js  c++  java
  • MySQL最左前缀索引

    # 建立组合索引
    CREATE TABLE t3
    (
        id    INT NOT NULL,
        username CHAR(30) NOT NULL,
        age  INT NOT NULL,
        info VARCHAR(255),
        INDEX MultiIdx(id, username, info(100)) # 组合索引遵循最左前缀原则
    );
    
    # 走索引id和username的组合索引
    EXPLAIN SELECT * FROM t3 WHERE id=1 AND username='zs'G;
    
    *************************** 1. row ***************************
               id: 1
      select_type: SIMPLE
            table: t3
       partitions: NULL
             type: ref
    possible_keys: MultiIdx
              key: MultiIdx
          key_len: 94
              ref: const,const
             rows: 1
         filtered: 100.00
            Extra: NULL
    1 row in set, 1 warning (0.01 sec)
    
    # 由于不存在username,因此只对id进行索引
    EXPLAIN SELECT * FROM t3 WHERE id=1 AND info='man'G; 
    
    *************************** 1. row ***************************
               id: 1
      select_type: SIMPLE
            table: t3
       partitions: NULL
             type: ref
    possible_keys: MultiIdx
              key: MultiIdx
          key_len: 4
              ref: const
             rows: 1
         filtered: 50.00
            Extra: Using where
    1 row in set, 1 warning (0.01 sec)
    
    # 由于最左前缀id不存在,因此不走索引MultiIdx
    EXPLAIN SELECT * FROM t3 WHERE username='zs' AND info='man'; 
    *************************** 1. row ***************************
               id: 1
      select_type: SIMPLE
            table: t3
       partitions: NULL
             type: ALL
    possible_keys: NULL
              key: NULL
          key_len: NULL
              ref: NULL
             rows: 2
         filtered: 50.00
            Extra: Using where
    1 row in set, 1 warning (0.01 sec)
    
    # 即使索引组合是乱序,只要存在最左前缀MySQL就会对其进行索引组合优化
    EXPLAIN SELECT * FROM t3 WHERE username='zs' AND id=1 AND info='man'; 
    
    *************************** 1. row ***************************
               id: 1
      select_type: SIMPLE
            table: t3
       partitions: NULL
             type: ref
    possible_keys: MultiIdx
              key: MultiIdx
          key_len: 397
              ref: const,const,const
             rows: 1
         filtered: 100.00
            Extra: Using where
    1 row in set, 1 warning (0.01 sec)
    
  • 相关阅读:
    python实现kNN(最近邻)
    拉格朗日对偶
    拉格朗日乘子法和KKT约束
    python实现支持向量机之具体实现
    python实现支持向量机之非线性支持向量机和核函数(理论五)
    Python 装饰器实例
    Linux 系统下 matplotlib 中文乱码解决办法
    Python logging 模块学习
    Matplotlib 知识点整理
    Python Matplotlib 中文显示参数设置
  • 原文地址:https://www.cnblogs.com/code-duck/p/14471686.html
Copyright © 2011-2022 走看看