Mysql 的简单索引学习及使用

一、创建表后,自行录入数据。

-- 创建表order_info
DROP TABLE IF EXISTS `order_info`;
CREATE TABLE `order_info` (
  `orderInfoId` bigint(20) NOT NULL AUTO_INCREMENT,
  `externalOrderId` varchar(30) DEFAULT NULL,
  `externalQueryId` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`orderInfoId`)
) ENGINE=InnoDB AUTO_INCREMENT=1168326 DEFAULT CHARSET=utf8mb4;

二、创建唯一索引,测试并查看执行计划。

-- 创建唯一索引,其中(order_info_externalQueryId)为索引名,(order_info)为表名,(externalQueryId)为列名
CREATE UNIQUE INDEX order_info_externalQueryId ON order_info(externalQueryId)

-- 删除创建的唯一索引,其中(order_info_externalQueryId)为索引名
drop index order_info_externalQueryId on order_info ;

-- 查看执行计划
EXPLAIN select a.orderInfoId,a.externalOrderId,a.externalQueryId 
from order_info a 
where a.externalQueryId = '20200710184819300073'

三、创建多列索引,测试并查看执行计划。

-- 创建多列索引,其中(order_info_externalOrderId_externalQueryId)为索引名,(order_info)为表名,(externalOrderId,externalQueryId)为列名
create index order_info_externalOrderId_externalQueryId on order_info (externalOrderId,externalQueryId) ;

-- 删除多列索引 
drop index order_info_externalOrderId_externalQueryId on order_info ;

-- 查看执行计划
EXPLAIN select a.orderInfoId,a.externalOrderId,a.externalQueryId 
from order_info a 
where a.externalOrderId = '200524588688' and a.externalQueryId = '20200710202245301700'

四、创建前缀索引,测试并查看执行计划。

-- 创建前缀索引,其中(order_info_prefix_description)为索引名,(order_info)为表名,(description)为列名,(10)前缀长度
create index order_info_prefix_description on order_info (description(10)) ;

-- 删除前缀索引,其中(order_info_prefix_description)为索引名
drop index order_info_prefix_description on order_info ;

-- 查看执行计划
EXPLAIN select a.orderInfoId,a.externalOrderId,a.externalQueryId 
from order_info a 
where a.description like '阿克苏%'
原文地址:https://www.cnblogs.com/nginxTest/p/13300181.html