首页 > 数据库 >MySQL联合索引最左匹配原则

MySQL联合索引最左匹配原则

时间:2024-07-07 09:27:47浏览次数:14  
标签:NAME employees 192.168 左匹配 索引 MySQL NULL type

MySQL中的联合索引(也叫组合索引)遵循最左匹配原则,即在创建联合索引时,查询条件必须从索引的最左边开始,否则索引不会被使用。在联合索引的情况下,数据是按照索引第一列排序,第一列数据相同时才会按照第二列排序。

例如,假设有一个表t_employees,它有一个联合索引(first_name, last_name)。

([email protected])[superdb]> create table t_employees as select EMPLOYEE_ID,FIRST_NAME,LAST_NAME,SALARY from employees;
Query OK, 91 rows affected (0.06 sec)
Records: 91  Duplicates: 0  Warnings: 0

([email protected])[superdb]> select * from t_employees;
+-------------+-------------+-------------+----------+
| EMPLOYEE_ID | FIRST_NAME  | LAST_NAME   | SALARY   |
+-------------+-------------+-------------+----------+
|         116 | Shelli      | Baida       |  2900.00 |
|         117 | Sigal       | Tobias      |  2800.00 |
|         118 | Guy         | Himuro      |  2600.00 |
|         119 | Karen       | Colmenares  |  2500.00 |
|         120 | Matthew     | Weiss       |  8000.00 |
|         121 | Adam        | Fripp       |  8200.00 |
|         122 | Payam       | Kaufling    |  7900.00 |
|         123 | Shanta      | Vollman     |  6500.00 |
|         124 | Kevin       | Mourgos     |  5800.00 |
|         125 | Julia       | Nayer       |  3200.00 |
|         126 | Irene       | Mikkilineni |  2700.00 |
|         127 | James       | Landry      |  2400.00 |
|         128 | Steven      | Markle      |  2200.00 |
|         129 | Laura       | Bissot      |  3300.00 |
|         130 | Mozhe       | Atkinson    |  2800.00 |
|         131 | James       | Marlow      |  2500.00 |
|         132 | TJ          | Olson       |  2100.00 |
|         133 | Jason       | Mallin      |  3300.00 |
|         134 | Michael     | Rogers      |  2900.00 |
|         135 | Ki          | Gee         |  2400.00 |
|         136 | Hazel       | Philtanker  |  2200.00 |
|         137 | Renske      | Ladwig      |  3600.00 |
|         138 | Stephen     | Stiles      |  3200.00 |
|         139 | John        | Seo         |  2700.00 |
|         140 | Joshua      | Patel       |  2500.00 |
|         141 | Trenna      | Rajs        |  3500.00 |
|         142 | Curtis      | Davies      |  3100.00 |
|         143 | Randall     | Matos       |  2600.00 |
|         144 | Peter       | Vargas      |  2500.00 |

([email protected])[superdb]> alter
 table t_employees add constraint pk_t_employees_id primary key(EMPLOYEE_ID);
Query OK, 0 rows affected (0.10 sec)
Records: 0  Duplicates: 0  Warnings: 0

([email protected])[superdb]> create index indx_t_employees_nameinfo on t_employees(FIRST_NAME,LAST_NAME);
Query OK, 0 rows affected (0.14 sec)
Records: 0  Duplicates: 0  Warnings: 0

([email protected])[superdb]> show index from t_employees;
+-------------+------------+---------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table       | Non_unique | Key_name                  | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-------------+------------+---------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| t_employees |          0 | PRIMARY                   |            1 | EMPLOYEE_ID | A         |          91 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| t_employees |          1 | indx_t_employees_nameinfo |            1 | FIRST_NAME  | A         |          79 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
| t_employees |          1 | indx_t_employees_nameinfo |            2 | LAST_NAME   | A         |          91 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
+-------------+------------+---------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
3 rows in set (0.01 sec)

1、满足联合索引最左匹配原则

以下查询会使用这个联合索引:
SELECT * FROM t_employees WHERE first_name = ‘James’;
SELECT * FROM t_employees WHERE first_name = ‘James’ AND last_name = ‘Marlow’;

([email protected])[superdb]> explain SELECT * FROM t_employees WHERE first_name = 'James';
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-------+
| id | select_type | table       | partitions | type | possible_keys             | key                       | key_len | ref   | rows | filtered | Extra |
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | t_employees | NULL       | ref  | indx_t_employees_nameinfo | indx_t_employees_nameinfo | 83      | const |    2 |   100.00 | NULL  |
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

([email protected])[superdb]> explain SELECT * FROM t_employees WHERE first_name = 'James' and LAST_NAME='Marlow';
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------------+------+----------+-------+
| id | select_type | table       | partitions | type | possible_keys             | key                       | key_len | ref         | rows | filtered | Extra |
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------------+------+----------+-------+
|  1 | SIMPLE      | t_employees | NULL       | ref  | indx_t_employees_nameinfo | indx_t_employees_nameinfo | 185     | const,const |    1 |   100.00 | NULL  |
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------------+------+----------+-------+
1 row in set, 1 warning (0.01 sec)

但是,下面的查询不会使用联合索引:
SELECT * FROM t_employees WHERE LAST_NAME=‘Marlow’;

([email protected])[superdb]>  explain SELECT * FROM t_employees WHERE LAST_NAME='Marlow';
+----+-------------+-------------+------------+------+---------------+------+---------+------+------+----------+-------------+
| id | select_type | table       | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra       |
+----+-------------+-------------+------------+------+---------------+------+---------+------+------+----------+-------------+
|  1 | SIMPLE      | t_employees | NULL       | ALL  | NULL          | NULL | NULL    | NULL |   91 |    10.00 | Using where |
+----+-------------+-------------+------------+------+---------------+------+---------+------+------+----------+-------------+
1 row in set, 1 warning (0.01 sec)

因为它们没有从索引的最左边开始。在联合索引的情况下,数据是按照索引第一列排序,第一列数据相同时才会按照第二列排序。

下面的查询会使用联合索引

([email protected])[superdb]> explain SELECT * FROM t_employees WHERE LAST_NAME='Marlow' and first_name = 'James';
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------------+------+----------+-------+
| id | select_type | table       | partitions | type | possible_keys             | key                       | key_len | ref         | rows | filtered | Extra |
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------------+------+----------+-------+
|  1 | SIMPLE      | t_employees | NULL       | ref  | indx_t_employees_nameinfo | indx_t_employees_nameinfo | 185     | const,const |    1 |   100.00 | NULL  |
+----+-------------+-------------+------------+------+---------------------------+---------------------------+---------+-------------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)

联合索引要能正确使用需要遵循最左匹配原则,也就是按照最左优先的方式进行索引的匹配。需要注意的是,因为有查询优化器,所以 first_name,last_name 字段在 where 子句的顺序并不重要

2、联合索引不遵循最左匹配原则,也是走全扫描二级索引树

我们都知道联合索引要遵循最左匹配才能走索引,但是如果数据库表中的字段都是索引的话,即使查询过程中,没有遵循最左匹配原则,也是走全扫描二级索引树(type=index)

如下的表结构及查询

([email protected])[superdb]> create table t_emplist as select EMPLOYEE_ID,FIRST_NAME,LAST_NAME from employees;
Query OK, 91 rows affected (0.10 sec)
Records: 91  Duplicates: 0  Warnings: 0

([email protected])[superdb]> alter table t_emplist add constraint pk_t_emplist_id primary key(EMPLOYEE_ID);
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

([email protected])[superdb]> create index indx_t_emplist_nameinfo on t_emplist(FIRST_NAME,LAST_NAME);
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

如下面的查询会使用联合索引,但不是最左匹配原则
SELECT * FROM t_emplist WHERE LAST_NAME=‘Marlow’;

([email protected])[superdb]> explain SELECT * FROM t_emplist WHERE LAST_NAME='Marlow';
+----+-------------+-----------+------------+-------+-------------------------+-------------------------+---------+------+------+----------+--------------------------+
| id | select_type | table     | partitions | type  | possible_keys           | key                     | key_len | ref  | rows | filtered | Extra                    |
+----+-------------+-----------+------------+-------+-------------------------+-------------------------+---------+------+------+----------+--------------------------+
|  1 | SIMPLE      | t_emplist | NULL       | index | indx_t_emplist_nameinfo | indx_t_emplist_nameinfo | 185     | NULL |   91 |    10.00 | Using where; Using index |
+----+-------------+-----------+------------+-------+-------------------------+-------------------------+---------+------+------+----------+--------------------------+
1 row in set, 1 warning (0.01 sec)

如果数据库表中的字段只有主键+二级索引,那么即使查询的where条件不满足最左匹配原则,也不会走全表扫描(type=all),而是走全扫描二级索引树(type=index)。

关键还是看数据表中的字段及索引情况。

标签:NAME,employees,192.168,左匹配,索引,MySQL,NULL,type
From: https://blog.csdn.net/zxrhhm/article/details/140240993

相关文章

  • MySQL使用LIKE索引是否失效的验证
    1、简单的示例展示在MySQL中,LIKE查询可以通过一些方法来使得LIKE查询能够使用索引。以下是一些可以使用的方法:使用前导通配符(%),但确保它紧跟着一个固定的字符。避免使用后置通配符(%),只在查询的末尾使用。使用COLLATE来控制字符串比较的行为,使得查询能够使用索引。下......
  • mysql执行查询的过程解析
    mysql执行查询的过程客户端先发送查询语句给服务器服务器检查缓存,如果存在则返回进行sql解析,生成解析树,再预处理,生成第二个解析树,最后再经过优化器,生成真正的执行计划根据执行计划,调用存储引擎的API来执行查询将结果返回给客户端。一、客户端到服务端之间的原理客户端和服......
  • 安装MySQL(Windows10和Linux CentOS7) 很详细的
    Windows10下安装MySQL1.下载MySQL官网下载MySQL:https://www.mysql.com/进入官网点击DOWNLOADS下滑点击MySQLCommunity(GPL)Downloads点击MySQLInstallerforWindows选择版本下载这里就不需要登录注册了,直接下载2.安装MySQL找到下载的文件双击之后选择Se......
  • MySQL 集群
    MySQL集群有多种类型,每种类型都有其特定的用途和优势。以下是一些常见的MySQL集群解决方案:1. MySQLReplication描述:MySQL复制是一种异步复制机制,允许将一个MySQL数据库的数据复制到一个或多个从服务器。用途:用于数据备份、读取负载均衡和灾难恢复。特点:简单易配......
  • 玄机第二章mysql应急响应
    玄机第二章mysql应急响应1.黑客第一次写入的shellflag{关键字符串}2.黑客反弹shell的ipflag{ip}3.黑客提权文件的完整路径md5flag{md5}注/xxx/xxx/xxx/xxx/xxx.xx4.黑客获取的权限flag{whoami后的值}flag1:数据库写shell在网站根目录比如intooutfileselect......
  • centos7.9 yum mysql8
    centos7.9mysql8安装CentOS7.9上安装MySQL8.0的步骤如下:下载MySQL官方的YumRepository:wgethttps://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm添加MySQLYumRepository到你的系统:sudorpm-Uvhmysql80-community-release-el7-3.noarch.rpm安......
  • MySQL锁
    MySQL锁1.前言锁是计算机在执行多线程或线程时用于并发访问同一共享资源时的同步机制,MySQL中的锁是在服务器层或者存储引擎层实现的,保证了数据访问的一致性与有效性MySQL锁可以按模式分类为:乐观锁与悲观锁。按粒度分可以分为全局锁、表级锁、页级锁、行级锁。按属性可以分为:共......
  • MySQL日志
    MySQL日志1.MySQL六种日志:重做日志(redolog)回滚日志(undolog)归档日志(binlog)错误日志(errorlog)慢查询日志(slowquerylog)一般查询日志(generallog)中继日志(relaylog)对MySQL来说,逻辑备份日志(binlog)、重做日志(redolog)、回滚日志(undolog)、锁技术+MVCC原子性:通过undolog......
  • centos7服务器yum安装MySQL数据库,以及报错的解决方案
    文章目录1、数据库能做什么?2、数据库由来3、数据库-系统结构4、版本二、部署1、官网地址3.点击[DOCUMENTATION](https://dev.mysql.com/doc/)4.mysql的yum仓库[UsingtheMySQLYumRepository](https://dev.mysql.com/doc/refman/8.4/en/linux-installation-yum-repo......
  • 零基础学习MySQL---表的相关操作
    顾得泉:个人主页个人专栏:《Linux操作系统》 《C++从入门到精通》  《LeedCode刷题》键盘敲烂,年薪百万!一、创建表1.语法CREATETABLEtable_name(field1datatype,field2datatype,field3datatype)characterset字符集collate校验规则engine存......