好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

mysql慢查询优化

是否记录查询日志 show variables like ‘ slow_query_log ‘ ; -- 是否记录未使用索引的查询 show variables like ‘ log_queries_not_using_indexes ‘ ; -- 开启 set GLOBAL log_queries_not_using_indexes = on ; -- 查询时间 show variables like ‘ long_query_time ‘ ; -- 超过0.1秒的查询记录 set GLOBAL long_query_time = 0.1 ; -- 开启 set GLOBAL slow_query_log = on ; -- 查看日志位置 show variables like ‘ slow_query_log_file ‘ ; SELECT * from t_activity LIMIT 11 ; -- 慢查询格式 # Time: 210219 14 : 18 : 50 -- 执行sql主机信息 # User @Host : root [ root ] @ WIN - DV0VLS73PNK [ 192.168.1.175 ] -- sql执行信息 # Query_time: 0.000000 Lock_time: 0.000000 Rows_sent: 6 Rows_examined: 6 -- 执行时间 SET timestamp = 1613715530 ; -- 内容 SELECT * from t_activity LIMIT 11 ;

二、日志分析

 

三、sql分析

使用explain查询sql的执行计划

EXPLAIN  SELECT   *   from   t_activity;
           id:   1  
  select_type: SIMPLE
          table  : t_activity   
         type:   ALL        
possible_keys:   NULL       
           key :  NULL        
      key_len:   NULL        
          ref:   NULL        
         rows:   6       

 

 

 

 

 

 

 

const 常数查找,一般主键唯一索引;

eq_reg 范围查找,主键或唯一索引范围查找;

ref 连接的查找,基于某一个索引的查找;

range 基于索引的范围查找;

index 索引的扫描;

all 表扫描;

四、优化

  1、max()优化

 SELECT   MAX (create_time)  from   t_activity;
  --   创建索引 
 CREATE   INDEX  idx_create_time  on  t_activity(create_time);

  2、count()优化

count(*) 会包含空,count(id)不包含空。也就是  count 一个可为空的字段时,只记录不为 null 的总合。

 select  
 COUNT (CHAPTER_STATE  !=   ‘  300225  ‘  ) ,
  COUNT (CHAPTER_STATE  in  ( ‘  300221  ‘ , ‘  300224  ‘ , ‘  300226  ‘  )) 
  from  t_course_chapter_info;

  3、子查询优化

通常情况下,需要把子查询优化为join查询,但是优化是要注意是否是一对多的关系,注意重复数据。

  4、limit 优化

    1)、使用有索引的列或者主键进行order by 操作

    2)、记录上次返回的主键,在下次查询是使用

四、索引优化

  如何选择合适的列建立索引:

  1.在where从句,group by 从句,order by 从句,on 从句中出现的列

  2.索引字段越小越好

  3.离散度大的列放到联合索引的前面 ,count(字段)越高离散度越大。

 

mysql慢查询优化

标签:字段   使用   连接   bsp   info   min   idt   chap   pre   

查看更多关于mysql慢查询优化的详细内容...

  阅读:40次