索引

① 编写SQL ② SQL优化(查询数据把查询时间缩短)

TB级别,10s => 0.01s

1、索引概述

索引作用: 快速检索数据(提高查询效率),InnoDB引擎其底层主要是使用B+ Tree结构

2、普通索引使用

主键就是一个索引,比如百万条数据,没有主键索引,查询可能需要3-5s,如果我们添加了主键索引且刚好,要查询的字段就是主键,则可以缩短到零点零几秒。

备注:主键、外键、唯一键其实也是索引

  • 创建索引:
    create index index_cname on category(cname);
    create index index_cname on category(cname(20));
  • 修改表添加索引:alter table category add index index_cname(cname(20));
  • 查询索引:show index from category;
  • 删除索引:drop index index_cname on category;
  • 查看所有库或者表的索引:
# 了解: mysql 是系统自带的数据库。innodb_index_stats 表记录 innodb 引擎(数据库核心) 的 索引状态.
# 查看数据库的所有索引:
select *
from mysql.innodb_index_stats where database_name="bigdata_db";

# 查看数据表的所有索引:
select *
from mysql.innodb_index_stats where database_name="bigdata_db" and table_name="products";

3、唯一索引使用

  • 创建索引
    create unique index index_cname on category(cname(20));
    alter table category add unique index index_cname(cname(20));
  • 删除索引
  drop index index_cname on category;
  alter table category drop index index_cname;

扩展:性能监测

-- 开启运行时间监测:
set profiling=1;
-- 查找第1万条数据ha-99999
select * from tb_index where title='ha-99999';
-- 查看执行的时间:
show profiles;
-- 给title字段创建索引:
alter table tb_index add index (title);
-- 再次执行查询语句
select * from test_index where title='ha-99999';
-- 再次查看执行的时间
show profiles;

4、索引使用注意

  • 索引不是越多越好. 索引使用应该注意以下问题:
    • 磁盘空间消耗
    • 创建索引和维护索引的时间消耗
    • 经常增删改数据,索引需要动态维护,效率低下。
    • 不经常查询的字段不需要创建索引
    • 大部分值相同的字段不需要创建索引
  • 扩展:
    • 开启mysql时间检测: set profiling=1;
    • 查看sql语句执行时间: show profiles;

相关推荐

  1. 索引

    2024-07-11 14:38:04       19 阅读
  2. MongoDB-索引-部分索引

    2024-07-11 14:38:04       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-11 14:38:04       53 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-11 14:38:04       56 阅读
  3. 在Django里面运行非项目文件

    2024-07-11 14:38:04       46 阅读
  4. Python语言-面向对象

    2024-07-11 14:38:04       57 阅读

热门阅读

  1. 嵌入式Bootloader面试题面面观(2万字长文)

    2024-07-11 14:38:04       22 阅读
  2. 1.python基础

    2024-07-11 14:38:04       20 阅读
  3. 24/07/11数据结构(6.1215)双链表实现-栈实现

    2024-07-11 14:38:04       21 阅读
  4. Spring框架:核心概念与Spring Boot微服务开发指南

    2024-07-11 14:38:04       17 阅读
  5. 解决Spring Boot中的数据安全与加密

    2024-07-11 14:38:04       21 阅读
  6. Flask和Django两个Web框架的特点和适用场景

    2024-07-11 14:38:04       22 阅读
  7. 直升机停机坪的H代表什么

    2024-07-11 14:38:04       16 阅读
  8. AcWing 187. 导弹防御系统

    2024-07-11 14:38:04       21 阅读