(1)mysql優化之sql性能問題定位

概述

我們面對一個問題的時候,首先是發現問題,然後纔是解決問題。在這篇文章中,主要解決如何定位問題。

解決方法

1.通過show status瞭解各種sql執行頻率

show status [like 'com_%'];

Com_xxx表示每個xxx語句執行的次數。
具體參數,參見:
http://lxneng.iteye.com/blog/451985
http://www.sandzhang.com/blog/2010/04/07/mysql-show-status-explained-detail/
show status

2.通過explain分析低效的SQL

explain sql_statement;

mysql explain
參數關係

參數 解釋
select_type 表示查詢的類型 simple-簡單表,primary-主查詢,union-union中的第二個查詢,subquery-子查詢
table 查詢的表 -
type 訪問類型 all-全表掃描,index-索引全掃描,range-索引範圍掃描,ref-使用非唯一索引或(唯一索引的前綴)掃描,eq_ref-唯一索引掃描,const/system-單表最多有一行匹配,null-不用訪問表或索引,就能直接得到結果
possible_keys 查詢時候可能使用到的索引 -
key 實際使用的索引 -
key_len 使用索引字段長度 -
rows 掃描行的數量 -
extra 執行情況說明和描述 -

3.explain extended 和 show warnings

explain extended sql_statement;
show warnings;

這裏寫圖片描述
這裏寫圖片描述
explain extended輸出結果相比explain多了filtered字段(所有結果行數/查詢結果行數*100),show warning的message字段可以看到sql優化器優化的結果。

4.通過 show profile分享sql

#查看是否mysql支持profile
SELECT @@have_profiling;

#查看是否開啓profiling
select @@profiling;

#查看profile
show profiles;

#查看某一個具體的query的profile,n-查詢id;
show profile for query n;

這裏寫圖片描述
這裏寫圖片描述

Sending data狀態表示mysql線程開始訪問數據行並把結果返回給客戶端,而不僅僅是返回結果給客戶端。

5.通過trace分析器分析

#開啓trace,設置格式爲json,設置trace能使用的最大內存大小。
set optimizer_trace="enabled=on",end_markers_in_json=on;
set optimizer_trace_max_mem_size=100000;

#檢查trace
SELECT * FROM information_schema.OPTIMIZER_TRACE;

這裏寫圖片描述

6.慢查詢日誌

發佈了63 篇原創文章 · 獲贊 37 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章