SQL - 索引

  • 索引本质上是数据库引擎用来快速查找数据的数据结构,可以显著提高查询的性能,为了加快运行较慢的查询。

  • 创建索引

    • 默认索引

      • create index 索引名 on 表名 (列名);
      • 通过对列名进行创建索引,在查询的时候,数据库就能通过索引找到匹配的那些行,适用于支持高效的范围查询。
      sql 复制代码
      -- 默认索引
      create index idx_points on customers (points);
      select customer_id
      from customers
      where points>1000;
    • 前缀索引

      • create index idx_last_name on customers (last_name(5));
      • 对于长字符串列,建议使用前缀索引来节省存储空间和提高查询效率。前缀索引只索引字符串的前几个字符。
      sql 复制代码
      --前缀索引
      create index idx_last_name on customers (last_name(5));
      select customer_id
      from customers
      where last_name like 'boa%';
    • 全文索引

      • create fulltext index idx_title_body on posts(title,body);
      • 全文索引可以在应用程序里打造快速强大的搜索引擎,适用于需要高效文本搜索,如文章,博客等。
      sql 复制代码
      -- 全文索引
      create fulltext index idx_title_body on posts(title,body);
      select *,match(title,body) against ('react redux')
      from posts
      -- where match (全文索引的列名(所有)) against(关键词)
      
      -- where match(title,body) against ('react redux')	
      -- 表示包含 'react' 或 'redux' 的记录
      
      where match(title,body) against('react -redux +form' in boolean mode) 
      -- 表示包含 'react' ,不包含 'redux',必须包含'form' 的记录
    • 复合索引

      • create index idx_state_points on customers (state,points);
      • 复合索引也叫组合索引,就是对多个列建立一个索引,遵循最左前缀原则,适用于需要在多个列进行查询的场景,显著提高查询效率。
      sql 复制代码
      -- 复合索引
      create index idx_state_points on customers (state,points);
      explain select customer_id
      from customers
      where state='ca' and points>1000;
  • 删除索引

    • drop index idx_state on customers;
  • 使用索引排序

    • 使用索引对数据进行排序,当你在添加索引时,MySQL会获取该列中的所有值,对其排序,并将它们存储在索引中。
  • 覆盖索引

    • 一个包含所有满足查询需要的数据的索引,数据库可以直接从索引中获取数据,避免了回表操作,显著提高查询性能。
  • 维护索引

    • 索引可以极大地提高查询的性能,但要注意在创建新索引之前,要先查看现有索引,否则容易产生"重复索引"和"多余索引"。
    • "重复索引",指同一组列上且顺序一致的索引,对于该索引应删除。
    • "多于索引",指多个索引的前缀列相同,或复合索引中包含了主键的索引,对于该索引应合并。
相关推荐
三不原则11 分钟前
故障案例:数据库慢查询导致交易延迟,AIOps 如何自动定位?
运维·数据库
Elieal16 分钟前
MybatisPlus难懂点
数据库·mybatis
一只专注api接口开发的技术猿23 分钟前
微服务架构下集成淘宝商品 API 的实践与思考
java·大数据·开发语言·数据库·微服务·架构
AC赳赳老秦29 分钟前
Dify工作流+DeepSeek:运维自动化闭环(数据采集→报告生成)
android·大数据·运维·数据库·人工智能·golang·deepseek
明洞日记31 分钟前
【软考每日一练009】计算机系统性能评价:基准程序分类与 TPC 实战案例详解
大数据·数据库
Hoxy.R1 小时前
海量数据库安装部署初体验
服务器·网络·数据库
癫狂的兔子1 小时前
【Python】【爬虫】爬取虎扑网NBA排行数据
数据库·爬虫·python
你才是臭弟弟1 小时前
时序数据库(TDengine TSDB)基本SQL使用
sql·时序数据库·tdengine
迷路剑客1 小时前
ES-7.10-高亮HighLight知识点总结
java·数据库·mybatis
程序边界1 小时前
解锁时序数据新玩法:金仓数据库实战体验分享
数据库