百度360必应搜狗淘宝本站头条
当前位置:网站首页 > IT技术 > 正文

mysql的表索引相关(mysql索引的用法)

wptr33 2025-05-03 16:58 18 浏览

索引的创建以及删除

1.alter table

2.create/drop index

mysql> create index idx_b on t (cls_id);
ERROR 1072 (42000): Key column 'cls_id' doesn't exist in table

desc方式查看

mysql> desc students;
+------------+-----------------+------+-----+---------+----------------+
| Field      | Type            | Null | Key | Default | Extra          |
+------------+-----------------+------+-----+---------+----------------+
| id         | bigint unsigned | NO   | PRI | NULL    | auto_increment |
| created_at | datetime(3)     | YES  |     | NULL    |                |
| updated_at | datetime(3)     | YES  |     | NULL    |                |
| deleted_at | datetime(3)     | YES  | MUL | NULL    |                |
| sno        | bigint          | YES  |     | NULL    |                |
| pwd        | varchar(32)     | NO   |     | NULL    |                |
| tel        | varchar(12)     | NO   |     | NULL    |                |
| birth      | datetime(3)     | YES  |     | NULL    |                |
| cls_id     | bigint          | YES  | MUL | NULL    |                |
+------------+-----------------+------+-----+---------+----------------+
9 rows in set (0.00 sec)
show create table 方式查看
mysql> show create table students;
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| Table    | Create Table                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
| students | CREATE TABLE `students` (
  `id` bigint unsigned NOT NULL AUTO_INCREMENT,
  `created_at` datetime(3) DEFAULT NULL,
  `updated_at` datetime(3) DEFAULT NULL,
  `deleted_at` datetime(3) DEFAULT NULL,
  `sno` bigint DEFAULT NULL,
  `pwd` varchar(32) NOT NULL,
  `tel` varchar(12) NOT NULL,
  `birth` datetime(3) DEFAULT NULL,
  `cls_id` bigint DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `idx_students_deleted_at` (`deleted_at`),
  KEY `idx_b` (`cls_id`)
) ENGINE=InnoDB AUTO_INCREMENT=50 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci |
+----------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

mysql> show index from students
    -> ;
+----------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table    | Non_unique | Key_name                | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+----------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| students |          0 | PRIMARY                 |            1 | id          | A         |          45 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| students |          1 | idx_students_deleted_at |            1 | deleted_at  | A         |           1 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
| students |          1 | idx_b                   |            1 | cls_id      | A         |           2 |     NULL |   NULL | YES  | BTREE      |         |               | YES     | NULL       |
+----------+------------+-------------------------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
3 rows in set (0.04 sec)

索引核心是降低io的操作

explain select的查询序列号

1.数字越小,表示最外面

2.数字越大表示优先级最高(最里面的先执行)

3.数字相同表示是同一组的 同一组里的按顺序来从上到下执行

mysql> explain select * from su a ,(select c2 from su where id=10) b where a.c2=b.c2;
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+-------+----------+-------------+
| id | select_type | table | partitions | type  | possible_keys | key     | key_len | ref   | rows  | filtered | Extra       |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+-------+----------+-------------+
|  1 | SIMPLE      | su    | NULL       | const | PRIMARY       | PRIMARY | 4       | const |     1 |   100.00 | NULL        |
|  1 | SIMPLE      | a     | NULL       | ALL   | NULL          | NULL    | NULL    | NULL  | 87778 |    10.00 | Using where |
+----+-------------+-------+------------+-------+---------------+---------+---------+-------+-------+----------+-------------+
2 rows in set, 1 warning (0.00 sec)

4.当type 中出现了all 表示走了全表扫描 possible_keys (可能用到的索引) key(索引名称) rows (扫描的行数 一般超过5000行就有问题需要进行优化)

5.update 或者delete也会使用到对应的索引(select,update,delete都是能加速的)


索引分为单列索引和联合索引

创建方法: create index idx_c3_c4 on su(c3,c4)

查看索引的信息:

mysql> show index from su;
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| Table | Non_unique | Key_name  | Seq_in_index | Column_name | Collation | Cardinality | Sub_part | Packed | Null | Index_type | Comment | Index_comment | Visible | Expression |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
| su    |          0 | PRIMARY   |            1 | id          | A         |      472487 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| su    |          1 | idx_c2    |            1 | c2          | A         |      305177 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| su    |          1 | idx_c3_c4 |            1 | c3          | A         |      304103 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
| su    |          1 | idx_c3_c4 |            2 | c4          | A         |      305613 |     NULL |   NULL |      | BTREE      |         |               | YES     | NULL       |
+-------+------------+-----------+--------------+-------------+-----------+-------------+----------+--------+------+------------+---------+---------------+---------+------------+
4 rows in set (0.03 sec)

查询

mysql> explain select * from su where c3="222";  #用到索引了
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key       | key_len | ref   | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | su    | NULL       | ref  | idx_c3_c4     | idx_c3_c4 | 4       | const |    2 |   100.00 | NULL  |
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.01 sec)

mysql> explain select * from su where c4="222";    #当使用c4查询时没有使用到对应的索引
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
|  1 | SIMPLE      | su    | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 472487 |    10.00 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

 explain select * from su where c4="222" order by c3;
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-----------------------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra                       |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-----------------------------+
|  1 | SIMPLE      | su    | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 472487 |    10.00 | Using where; Using filesort |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-----------------------------+
1 row in set, 1 warning (0.00 sec)

mysql> explain select * from su where c3="222" order by c4;
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------+
| id | select_type | table | partitions | type | possible_keys | key       | key_len | ref   | rows | filtered | Extra |
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------+
|  1 | SIMPLE      | su    | NULL       | ref  | idx_c3_c4     | idx_c3_c4 | 4       | const |    2 |   100.00 | NULL  |
+----+-------------+-------+------------+------+---------------+-----------+---------+-------+------+----------+-------+
1 row in set, 1 warning (0.00 sec)
#all 运算符没有使用到索引
mysql> explain select * from su where c3="222" or c4="123";
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
|  1 | SIMPLE      | su    | NULL       | ALL  | idx_c3_c4     | NULL | NULL    | NULL | 472487 |    19.00 | Using where |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
1 row in set, 1 warning (0.00 sec)

总结: 1.创建联合索引时 最左前缀原则 当单独使用c4时是无法使用索引的

2.在orderby 进行排序时也是遵循最左前缀原则的 走索引(c3必须在前面才行)

3.or 关键字在联合索引中不起作用(单列索引是可以) index merge(索引的合并),只能用一个索引(同时使用到单列和联合索引) 转化为 合并索引

4.不支持中文索引,但是支持全文索引如何创建全文索引

5.索引中不会包含有null值的列,当使用count(*)时对null值不走,对于创建索引时我们建议创建非空字段 不建议在null上的字段简历索引

6.在进行select语句时不要进行函数运算 ,否则你创建索引了也用不到索引

mysql> create index idx_c4 on su(c4);
Query OK, 0 rows affected (3.83 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> explain select * from su where c3="222" or c4="123";
+----+-------------+-------+------------+-------------+------------------+------------------+---------+------+------+----------+-------------------------------------------------+
| id | select_type | table | partitions | type        | possible_keys    | key              | key_len | ref  | rows | filtered | Extra                                           |
+----+-------------+-------+------------+-------------+------------------+------------------+---------+------+------+----------+-------------------------------------------------+
|  1 | SIMPLE      | su    | NULL       | index_merge | idx_c3_c4,idx_c4 | idx_c3_c4,idx_c4 | 4,4     | NULL |    3 |   100.00 | Using sort_union(idx_c3_c4,idx_c4); Using where |
+----+-------------+-------+------------+-------------+------------------+------------------+---------+------+------+----------+-------------------------------------------------+
1 row in set, 1 warning (0.01 sec)

删除索引: alter table su drop index idx_c4;

mysql> ALTER TABLE su drop index idx_c4;
Query OK, 0 rows affected (0.05 sec)
Records: 0  Duplicates: 0  Warnings: 0

尽量少使用or 否则就健单列索引

全文索引

create fulltext index idx_su on su(1);

覆盖索引

通过索引即可查到数据(就是覆盖素引) Extra 中使用 Usingindex

查询列就是索引列

mysql> explain select c2 from su where c2=123;
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key    | key_len | ref   | rows | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+
|  1 | SIMPLE      | su    | NULL       | ref  | idx_c2        | idx_c2 | 4       | const |    1 |   100.00 | Using index |
+----+-------------+-------+------------+------+---------------+--------+---------+-------+------+----------+-------------+

当extra 中使用的是 filesort 时需要优化

函数运算索引

mysql> explain select * from su where YEAR(C5)<2007;
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
| id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows   | filtered | Extra       |
+----+-------------+-------+------------+------+---------------+------+---------+------+--------+----------+-------------+
|  1 | SIMPLE      | su    | NULL       | ALL  | NULL          | NULL | NULL    | NULL | 497738 |   100.00 | Using where |
+----+-------------+-------+---------
  
  未使用函数时
  mysql> explain select * from su where C5<"2007-12-12:14:00";
+----+-------------+-------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
| id | select_type | table | partitions | type  | possible_keys | key    | key_len | ref  | rows | filtered | Extra                 |
+----+-------------+-------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
|  1 | SIMPLE      | su    | NULL       | range | idx_c5        | idx_c5 | 4       | NULL |    1 |   100.00 | Using index condition |
+----+-------------+-------+------------+-------+---------------+--------+---------+------+------+----------+-----------------------+
1 row in set, 2 warnings (0.00 sec)

1.提高排队效率

2.创建索引在非null的字段上进行创建,在有null的字段会扫描对应 的null数据

3.联合索引降低搜索的范围(单行索引和联合索引没有绝对的好与不好)

1.通过索引 扫描超过30%时走全表扫描

2.函数 以及模糊匹配时无法使用索引 like 语句

3.不综训最左前缀原则不走索引

4.两个单读索引 一个用排序 orderby 需要创建联合索引


相关推荐

redis的八种使用场景

前言:redis是我们工作开发中,经常要打交道的,下面对redis的使用场景做总结介绍也是对redis举报的功能做梳理。缓存Redis最常见的用途是作为缓存,用于加速应用程序的响应速度。...

基于Redis的3种分布式ID生成策略

在分布式系统设计中,全局唯一ID是一个基础而关键的组件。随着业务规模扩大和系统架构向微服务演进,传统的单机自增ID已无法满足需求。高并发、高可用的分布式ID生成方案成为构建可靠分布式系统的必要条件。R...

基于OpenWrt系统路由器的模式切换与网页设计

摘要:目前商用WiFi路由器已应用到多个领域,商家通过给用户提供一个稳定免费WiFi热点达到吸引客户、提升服务的目标。传统路由器自带的Luci界面提供了工厂模式的Web界面,用户可通过该界面配置路...

这篇文章教你看明白 nginx-ingress 控制器

主机nginx一般nginx做主机反向代理(网关)有以下配置...

如何用redis实现注册中心

一句话总结使用Redis实现注册中心:服务注册...

爱可可老师24小时热门分享(2020.5.10)

No1.看自己以前写的代码是种什么体验?No2.DooM-chip!国外网友SylvainLefebvre自制的无CPU、无操作码、无指令计数器...No3.我认为CS学位可以更好,如...

Apportable:拯救程序员,IOS一秒变安卓

摘要:还在为了跨平台使用cocos2d-x吗,拯救objc程序员的奇葩来了,ApportableSDK:FreeAndroidsupportforcocos2d-iPhone。App...

JAVA实现超买超卖方案汇总,那个最适合你,一篇文章彻底讲透

以下是几种Java实现超买超卖问题的核心解决方案及代码示例,针对高并发场景下的库存扣减问题:方案一:Redis原子操作+Lua脚本(推荐)//使用Redis+Lua保证原子性publicbo...

3月26日更新 快速施法自动施法可独立设置

2016年3月26日DOTA2有一个79.6MB的更新主要是针对自动施法和快速施法的调整本来内容不多不少朋友都有自动施法和快速施法的困扰英文更新日志一些视觉BUG修复就不翻译了主要翻译自动施...

Redis 是如何提供服务的

在刚刚接触Redis的时候,最想要知道的是一个’setnameJhon’命令到达Redis服务器的时候,它是如何返回’OK’的?里面命令处理的流程如何,具体细节怎么样?你一定有问过自己...

lua _G、_VERSION使用

到这里我们已经把lua基础库中的函数介绍完了,除了函数外基础库中还有两个常量,一个是_G,另一个是_VERSION。_G是基础库本身,指向自己,这个变量很有意思,可以无限引用自己,最后得到的还是自己,...

China&#39;s top diplomat to chair third China-Pacific Island countries foreign ministers&#39; meeting

BEIJING,May21(Xinhua)--ChineseForeignMinisterWangYi,alsoamemberofthePoliticalBureau...

移动工作交流工具Lua推出Insights数据分析产品

Lua是一个适用于各种职业人士的移动交流平台,它在今天推出了一项叫做Insights的全新功能。Insights是一个数据平台,客户可以在上面实时看到员工之间的交流情况,并分析这些情况对公司发展的影响...

Redis 7新武器:用Redis Stack实现向量搜索的极限压测

当传统关系型数据库还在为向量相似度搜索的性能挣扎时,Redis7的RedisStack...

Nginx/OpenResty详解,Nginx Lua编程,重定向与内部子请求

重定向与内部子请求Nginx的rewrite指令不仅可以在Nginx内部的server、location之间进行跳转,还可以进行外部链接的重定向。通过ngx_lua模块的Lua函数除了能实现Nginx...