MySQL_SQL性能分析

SQL执行频次

  1. 语法:

    sql 复制代码
    SHOW GLOBAL STATUS LIKE 'COM_+类型';
    COM_insert; 插入次数
    com_delete; 删除次数
    com_update; 更新次数
    com_select; 查询次数
    com_______; 
  2. 注意:通过语法,可以查询到数据库的实际状态,就可以知道数据库是以增删改为主,还是以查询为主,如果是以查询为主,就可以考虑sql 的索引优化。

慢查询日志(可以根据此日志看是否需要优化sql)

  1. 概述:慢查询日志记录了超过指定时间的查询sql,指定参数(long_query_time,单位是秒,默认值是10秒)

  2. 如何查看慢查询功能是否打开?

    sql 复制代码
    show variables like 'slow_query_log';


  3. 参数说明

    • slow-query-log=1 代表开启 =0 代表关闭
    • long_query_time=10 代表慢查询超过10秒日志会记录
    • slow_query_log_file 慢查询的日志文件
  4. 演示慢查询

    • 把慢查询打开 slow-query-log=1
    • 把慢查询时间设置段 1秒 long_query_time=1
    • 重启一下mysql 的服务
  5. 分析慢查询日志

    • 当sql 出现到慢查询日志中的时候,就可以考虑对这条sql 进行优化了。

Profile 详情

  1. 概述:show profiles 能够用来做SQL优化时,协助我们了解时间消耗

  2. 查看Profile 是否开启

    sql 复制代码
    select @@profiling;
  3. 设置profile开启

    sql 复制代码
    set [session/global] profiling=1
  4. 同过profile了解时间消耗

    sql 复制代码
    select * from user;
    select count(*) from user;
    select * from user where id = 10;
    select * from user where name = '荆轲'
    • 使用profiles文件观察时间消耗
      • show profiles;(每次执行,query_id 都会变)
      • show profile for query query_id;(注意query_id 是使用showprofiles 查询出来的)
      • show profile cpu for query query_id;可以查询cpu占用

explain

  1. explain 或者 desc 都可以获取select语句的查询信息

  2. 语法:

    sql 复制代码
    explain 查询语句


  • 演示 id 执行先后的

    sql 复制代码
    explain select * from emp where dept_id = (select id from dept where name = '研发部')
  • 演示 type(const 使用主键或者唯一索引的时候)

    sql 复制代码
    explain select id from dept where name = '研发部'; all
    
    explain select * from emp where id = 1;
    
    explain select * from user where phone = '13508895543'
  • key 演示

    sql 复制代码
    explain select * from user where id  > 5

    索引效率验证

  • 添加主键索引(添加的时候,需要维护索引数据,所以速度较慢)

    • 没有主键索引的时候耗时情况

    • 添加了主键索引的时候耗时情况

  • 给 name 字段添加索引列

    • name 没有添加索引列的时候

    • 给name 添加了索引列之后

  1. 结论:索引确实能提升查询速度,而且是质的提升。
相关推荐
九皇叔叔7 分钟前
MySQL 数据库 Read View 详解
数据库·mysql·mvcc·read view
Elastic 中国社区官方博客1 小时前
Elasticsearch:圣诞晚餐 BBQ - 图像识别
大数据·数据库·elasticsearch·搜索引擎·ai·全文检索
cui_win1 小时前
Prometheus实战教程 - Redis 监控
数据库·redis·prometheus
JIngJaneIL2 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
TG:@yunlaoda360 云老大2 小时前
华为云国际站代理商备份策略设置过程中遇到问题如何解决?
服务器·数据库·华为云
SelectDB2 小时前
Doris Catalog 已上线!性能提升 200x,全面优于 JDBC Catalog,跨集群查询迈入高性能分析时代
数据库·数据分析·apache
TAEHENGV2 小时前
进度跟踪模块 Cordova 与 OpenHarmony 混合开发实战
android·javascript·数据库
神秘面具男033 小时前
MySQL 从基础到实践
数据库·mysql
Hello.Reader3 小时前
Flink Process Table Functions(PTF)实战详解:把 SQL 变成“可编程算子”,状态、时间、定时器一把梭
网络·sql·flink
2301_767902644 小时前
MySQL 入门
数据库·mysql