MySQL慢查詢尋找和調優測試

來源:互聯網
上載者:User

編輯 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;

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.