红联Linux门户
Linux帮助

关于MySQL查询语句统计和查询缓存相关的状态值

发布时间:2015-03-09 21:39:32来源:linux网站作者:kaifly

关于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_blocksfree_memory可以告诉您属于哪种情况)。

Qcache_not_cached

不适合进行缓存的查询的数量,通常是由于这些查询不是SELECT语句以及由于query_cache_type设置的不会被Cache的查询,或者结果集超过query_cache_limit变量设置的语句。

Qcache_queries_in_cache

当前在query_cache中‘注册’的select语句条数

Qcache_total_blocks

缓存中块的总量。