mysql 代码怎么优化_MySQL 性能优化的简略办法
mysql 性能優(yōu)化的簡單辦法
優(yōu)化數(shù)據(jù)庫最核心的實際上就是配置參數(shù)的調整。本文通過一個簡單的參數(shù)調整,實現(xiàn)了對擁有一個幾十萬行表的 group by 優(yōu)化的例子。通過這個簡單的調整,數(shù)據(jù)庫性能有了突飛猛進的提升。
本例子是針對 MySQL 調整的,不像其他商業(yè)數(shù)據(jù)庫,MySQL 沒有視圖,特別是 Oracle 可以利用固化視圖來提升查詢性能,沒有存儲過程,因此性能的調整幾乎只能通過配置合適的參數(shù)來實現(xiàn)。
調整的具體步驟(例子針對 pLog 0.3x 的博客系統(tǒng)):
發(fā)現(xiàn)最多的 slow log 是:
SELECT category_id, COUNT(*) AS ‘count’ FROM plog_articles WHERE blog_id = 2 AND status = ‘PUBLISHED’ group by category_id;
一般在 20s 以上,甚至 30s 。
而當 blog_id=1 或者其他時,都能很快的選出結果。
于是懷疑索引有問題,重新建立索引,但無濟于事。 EXPLAIN 結果如下:
mysql> EXPLAIN SELECT category_id, COUNT(*) AS ‘count’ FROM plog_articles WHERE blog_id = 2 AND status = ‘PUBLISHED’ group by category_id;
+—————+——+——————+——————+———+————-+——+———————————————-+
| table | type | possible_keys | key | key_len | ref | rows | Extra |
+—————+——+——————+——————+———+————-+——+———————————————-+
| plog_articles | ref | idx_article_blog | idx_article_blog | 5 | const,const | 4064 | Using where; Using temporary; Using filesort |
+—————+——+——————+——————+———+————-+——+———————————————-+
1 row in set (0.00 sec)
于是想到每次查看 blog_id = 2 的博客時,系統(tǒng)負載就提高,有較高的 swap 。于是查看 temporary table 有關的資料,果然有這樣的說法:
If you create a lot of disk-based temporary tables, increase the size of tmp_table_size if you can do so safely. Keep in mind that setting the value too high may result in excessive swapping or MySQL running out of memory if too many threads attempt to allocate in-memory temporary tables at the same time. Otherwise, make sure that tmpdir points to a very fast disk that’s not already doing lots of I/O.
Another problem that doesn’t show up in the slow query log is an excessive use of disk-based temporary tables. In the output of EXPLAIN, you’ll often see Using temporary. It indicates that MySQL must create a temporary table to complete the query. However, it doesn’t tell you whether that temporary table will be in memory or on disk. That’s controlled by the size of the table and MySQL’s tmp_table_size variable.
If the space required to build the temporary table is less than or equal to tmp_table_size, MySQL keeps it in memory rather than incur the overhead and time required to write the data to disk and read it again. However, if the space required exceeds tmp_table_size, MySQL creates a disk-based table in its tmpdir directory (often /tmp on Unix systems.) The default tmp_table_size size is 32 MB.
To find out how often that happens, compare the relative sizes of the Created_tmp_tables and Created_tmp_disk_tables counters:
調整 tmp_table_size為 80M 左右后,以上語句 14s 即可解決。
原創(chuàng)文章,轉載請注明: 轉載自搞代碼
微信 賞一包辣條吧~
支付寶 賞一聽可樂吧~
總結
以上是生活随笔為你收集整理的mysql 代码怎么优化_MySQL 性能优化的简略办法的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql触发器行锁_MySQL 之 视
- 下一篇: mysql 挑战握手协议_什么是挑战握手