天天看點

mysql 查詢語句統計和查詢緩存相關的狀态值解疑答惑

關于mysql裡‘show global status’輸出的Com_select、Queries、Questions、Qcache_hits、Qcache_inserts、Qcache_not_cached這幾個狀态值一直有些迷惑,現通過實驗來更加準确和深刻的了解之。

實驗版本:5.5.39

先附上每個狀态的官方解釋

Com_select:The Com_xxx statement counter variables indicate the number of times each xxx statement hasbeen executed.However, if a query result is returned from query cache, the server increments the Qcache_hits status variable, not Com_select.

select語句執行的次數,如果結果從查詢緩存裡得來,就增加Qcache_hits,而不增加Com_select

Queries:The number of statements executed by the server. This variable includes statements executed within stored programs, unlike the Questions variable. It does not count COM_PING or COM_STATISTICS commands.

server執行過的所有語句,計數包含存儲存儲程式(存儲過程)裡面的sql條數

Questions:The number of statements executed by the server. This includes only statements sent to the server by clients and not statements executed within stored programs, unlike the Queries variable. This variable does not count COM_PING, COM_STATISTICS, COM_STMT_PREPARE, COM_STMT_CLOSE, or COM_STMT_RESET commands.

隻包含由client發過來的sql語句數量(包括use語句,show語句等),不包括存儲過程裡的sql語句(一個存儲過程作為一條語句)

Qcache_hits:The number of query cache hits.

查詢緩存命中的次數

Qcache_inserts:The number of queries added to the query cache.

加入到查詢緩存的次數

Qcache_not_cached:The number of noncached queries (not cacheable, or not cached due to the query_cache_type setting).

不可緩存的查詢數量。不可緩存的(例如結果集大小超過query_cache_limit的);或者由于query_cache_type設定(on  允許、off  不允許、demand  依賴明确指定的使用緩存)不能使用查詢緩存的數量。

Qcache_queries_in_cache:The number of queries registered in the query cache

在查詢緩存中‘注冊’過的查詢語句的條數

下面通過實驗來觀察個 狀态值的增長情況:

重新開機資料庫,清空查詢緩存

執行一條查詢語句,然後觀察個狀态值

Com_select    | 1

Qcache_hits   | 0

Qcache_inserts  | 1

在執行上面執行的查詢語句,個狀态值

Com_select 不變

Qcache_hits 加1

Qcache_inserts 不變

明确指定不使用緩存(加上SQL_NO_CACHE),執行剛才的查詢語句

Com_select 加1

Qcache_hits 不變

Qcache_not_cached 加1

在搞清楚了以上幾個值的含義後,讨論一下計算‘查詢緩存命中率’的公式,關于查詢緩存命中率的計算方法,網上說法不一,這裡說一下我的了解:

查詢語句分為‘可緩存’和‘不可緩存’兩種

可緩存的:若存在于query_cache中,則Com_select不變,Qcache_hits加1

          不存在于query_cache中,則Com_select加1,Qcache_inserts加1

不可緩存的:select加1,Qcache_not_cached加1

即 Com_select = Qcache_inserts+Qcache_not_cached

是以查詢緩存的命中率可以計算如下:

Qcache_hits/(Qcache_hits+Com_select)

附:查詢緩存變量含義:

Qcache_free_blocks

目前還處于空閑狀态的 Query Cache中記憶體Block 數目,數目大說明可能有碎片。FLUSH QUERY CACHE會對緩存中的碎片進行整理,進而得到一個空閑塊。

Qcache_free_memory

緩存中的空閑記憶體總量。

Qcache_hits

緩存命中次數。

Qcache_inserts

緩存失效次數(查詢結果新增進QueryCache的數量)

Qcache_lowmem_prunes

緩存出現記憶體不足并且必須要進行清理以便為Qcache_inserts動作騰出空間的次數,這個數字最好長時間來看;如果這個數字增長較快,就表示可能碎片非常嚴重,或者記憶體很少。(上面的free_blocks和free_memory可以告訴您屬于哪種情況)。

Qcache_not_cached

不适合進行緩存的查詢的數量,通常是由于這些查詢不是SELECT語句以及由于query_cache_type設定的不會被Cache的查詢,或者結果集超過query_cache_limit變量設定的語句。

Qcache_queries_in_cache

目前在query_cache中‘注冊’的select語句條數

Qcache_total_blocks

緩存中塊的總量。

     本文轉自kai404 51CTO部落格,原文連結:http://blog.51cto.com/kaifly/1592080,如需轉載請自行聯系原作者