暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

MySQL 组合索引

董源龙 2021-09-06
888

组合索引 高效建立组合索引,可以提高查询效率。

创建(a,b,c)3个字段的组合

可以使用

where

a=

或者

where

a=

b=

或者

where

a=

b=

c=

等条件查询

如果按照如下方式使用,不会走该索引

    EXPLAIN SELECT * from tb_test
    WHERE
    `b` = '1'
    and `c` = '1'
    order by `a`;
    复制


    如何建立索引

      select
      *
      from table
      where
      a=''
      and b=''
      order by c
      复制


      新建表

        CREATE TABLE `tb_test` (
        `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
        `name` varchar(255) DEFAULT NULL COMMENT '姓名',
        `age` int(11) DEFAULT '0' COMMENT '年龄',
        `address` varchar(255) DEFAULT NULL COMMENT '地址',
        `city` varchar(255) DEFAULT NULL COMMENT '所在城市',
        PRIMARY KEY (`id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='Test';
        复制


        如果建立 a,b组合索引

          KEY `idx_age_address` (`age`,`address`) USING BTREE
          复制



          Extre

          Using index condition; Using filesort

          id

          select_type

          table

          partitions

          type

          possible_keys

          key

          key_len

          ref

          rows

          filtered

          Extra

          1

          SIMPLE

          tb_test


          ref

          idx_age_address

          idx_age_address

          1028

          const,const

          1

          100

          Using index condition; Using filesort



          如果建立 a,b,c组合索引

            KEY `idx_age_address_name` (`age`,`address`,`name`) USING BTREE
            复制


            id

            select_type

            table

            partitions

            type

            possible_keys

            key

            key_len

            ref

            rows

            filtered

            Extra

            1

            SIMPLE

            tb_test


            ref

            idx_age_address_name

            idx_age_address_name

            1028

            const,const

            2

            100

            Using index condition

            Extre

            Using index condition


            对于order by c 排序

            如果将c加入到组合索引中。在执行计划内。MySQL执行计划将不执行Using filesort


            文章转载自董源龙,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

            评论