查询缓存

1、从Mysql4.0开始,支持查询缓存,把查询结果记录下来,遇到同样的查询直接返回,提高效率。
2、query_cache_type 查询缓存是否开启
select @@query_cache_type;
set @@query_cache_type=on;
3、have_query_cache 已经可用
select @@have_query_cache; // 变量是只读的
4、query_cache_size 缓存大小
query_cache_size 只有全局作用域,没有会话作用域。而且设置太小不起作用,单位是字节,如下:
mysql> set @@global.query_cache_size=10000;
Query OK, 0 rows affected

mysql> select @@global.query_cache_size;
+---------------------------+
| @@global.query_cache_size |
+---------------------------+
| 0 |
+---------------------------+
1 row in set

mysql> set @@global.query_cache_size=1000000;
Query OK, 0 rows affected

mysql> select @@global.query_cache_size;
+---------------------------+
| @@global.query_cache_size |
+---------------------------+
| 999424 |
+---------------------------+
1 row in set
5、query_cache_limit 控制查询结果的最大值,也就是说,查询结果超过一定大小,不缓存。
query_cache_limit只有全局作用域。
6、show status like 'qcache%'; // 这是状态变量,也就是mysql运行过程中的状态
记录查询缓存的相关信息,其中Qcache_queries_in_cache 是缓存结果的个数。
7、考虑下面的需求,在查询性能测试的时候,不希望有查询缓存,否则结果没有意义。怎么解决这个问题?
a、设置会话query_cache_type=off; 注意是会话query_cache_type,如果是全局query_cache_type,重连mysql才会起作用。
b、每次查询的时候,使用reset query cache,清除缓存信息,Qcache_queries_in_cache个数为0
c、使用sql_no_cache,告诉mysql不要缓存查询结果,Qcache_queries_in_cache个数不会增加,如下:
select sql_no_cache count(*) from student;
8、注意:Mysql只对查询和非常简单的存储过程(只包含简单的select),才进行缓存。比如:
// 进行缓存
BEGIN
select count(*) from student;
END

// 不进行缓存
BEGIN
declare i int default 0;
while (i<1) do
select count(*) from student;
set i = i+1;
end while;
END
9、某个操作会导致缓存中的记录无效,考虑下面的情况,
select count(*) from student;
delete from student where id = 100;
select count(*) from student;
这种情况,Mysql执行select count(*) from student;缓存增加一条记录,当执行 delete from student where id = 100;之后,
Mysql认为缓存记录select count(*) from student; 无效,删除这条记录,Qcache_queries_in_cache个数减1,下一次的查询
select count(*) from student; 重新执行一次。
10、注意:上面缓存的测试使用mysql客户端进行的,使用Navicat的时候,也要在新建查询中,
先执行一下set @@session.query_cache_type=off;

原文地址:https://www.cnblogs.com/nzbbody/p/4752037.html