索引

① 编写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;
  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值