MySQL慢查詢查找和調優測試。本站提示廣大學習愛好者:(MySQL慢查詢查找和調優測試)文章只能為提供參考,不一定能成為您想要的結果。以下是MySQL慢查詢查找和調優測試正文
編纂 my.cnf或許my.ini文件,去除上面這幾行代碼的正文:
log_slow_queries = /var/log/mysql/mysql-slow.log
long_query_time = 2
log-queries-not-using-indexes
這將使得慢查詢和沒有應用索引的查詢被記載上去。
如許做以後,對mysql-slow.log文件履行tail -f敕令,將能看到個中記載的慢查詢和未應用索引的查詢。
隨意提取一個慢查詢,履行explain:
explain low_query
你將看到上面的成果:
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
| 1 | SIMPLE | some_table | ALL | NULL | NULL | NULL | NULL | 166 | Using where |
+----+-------------+---------------------+------+---------------+------+---------+------+------+-------------+
留意下面的rows和key列。rows顯示該查詢影響了若干行記載,我們不想讓這個值太年夜。key顯示用了哪一個索引,為NULL時表現查詢未用任何索引。
假如想讓查詢更快,你也許須要為某些列增長索引:
CREATE INDEX myapp_mytable_myfield_idx on myapp_mytable(myfield);
除設置裝備擺設mysql設置裝備擺設文件來完成記載慢查詢外,還有上面的辦法可以記載慢查詢:
SELECT t.TABLE_SCHEMA AS `db`,
t.TABLE_NAME AS `table`,
s.INDEX_NAME AS `index name`,
s.COLUMN_NAME AS `FIELD name`,
s.SEQ_IN_INDEX `seq IN index`,
s2.max_columns AS `# cols`,
s.CARDINALITY AS `card`,
t.TABLE_ROWS AS `est rows`,
ROUND(((s.CARDINALITY / IFNULL(t.TABLE_ROWS, 0.01)) * 100), 2) AS `sel %`
FROM INFORMATION_SCHEMA.STATISTICS s
INNER JOIN INFORMATION_SCHEMA.TABLES t ON s.TABLE_SCHEMA = t.TABLE_SCHEMA AND s.TABLE_NAME = t.TABLE_NAME
INNER JOIN (
SELECT TABLE_SCHEMA, TABLE_NAME, INDEX_NAME, MAX(SEQ_IN_INDEX) AS max_columns
FROM INFORMATION_SCHEMA.STATISTICS
WHERE TABLE_SCHEMA != 'mysql' GROUP BY TABLE_SCHEMA, TABLE_NAME, INDEX_NAME ) AS s2 ON s.TABLE_SCHEMA = s2.TABLE_SCHEMA AND s.TABLE_NAME = s2.TABLE_NAME AND s.INDEX_NAME = s2.INDEX_NAME
WHERE t.TABLE_SCHEMA != 'mysql' /* Filter out the mysql system DB */
AND t.TABLE_ROWS > 10 /* Only tables with some rows */
AND s.CARDINALITY IS NOT NULL /* Need at least one non-NULL value in the field */
AND (s.CARDINALITY / IFNULL(t.TABLE_ROWS, 0.01)) < 1.00 /* unique indexes are perfect anyway */
ORDER BY `sel %`, s.TABLE_SCHEMA, s.TABLE_NAME /* DESC for best non-unique indexes */
LIMIT 10;