如何使用MYSQL语句进行数据缓存()

  1. 查询缓存设置
1) 验证服务器是否支持查询缓存
show variables like '%have_query_cache%';
| Variable_name | Value |
| have_query_cache | YES |
2) 查询缓存会受到以下3个系统变量值的影响
show variables like 'query_cache%';
| Variable_name | Value |
| query_cache_limit | 1048576 | //能够缓存的最大结果集大小
| query_cache_min_res_unit | 4096 |
| query_cache_size | 1048576 | //决定为查询缓存分配的内存大小
| query_cache_type | OFF | //决定查询缓存的操作方式
| query_cache_wlock_invalidate | OFF |
那么mysql到底是怎么决定到底要不要把查询结果放到查询缓存中呢?是根据query_cache_type这个变量来决定的。
这个变量有三个取值:0,1,2,分别代表了off、on、demand。
mysql默认为开启 on (1)
如果是0,那么query cache 是关闭的。
如果是1,那么查询总是先到查询缓存中查找,即使使用了sql_no_cache仍然查询缓存,因为sql_no_cache只是不缓存查询结果,而不是不使用查询结果。
如果是2,DEMAND没有使用sql_cache,好像仍然使用了查询缓存
结论:只要query_cache_type没有关闭,sql查询总是会使用查询缓存,如果缓存没有命中则开始查询的执行计划到表中查询数据。
  1. sql_cahce和sql_no_cache hints的使用
为了测试sql语句的效率,有时候要不用缓存来查询。
使用SELECT SQL_NO_CACHE ...语法即可
SQL_NO_CACHE的真正作用是禁止缓存查询结果,但并不意味着cache不作为结果返回给query。
目前的SQL_NO_CACHE有两种解释:
1.对当前query不使用手游数据库已有缓存来查询,则当前query花费时间会多点
2.对当前query的产生的结果集不缓存至系统query cache里,则下次相同query花费时间会多点
sql_cache意思是说,查询的时候使用缓存。
对SQL_NO_CACHE的解释及测试如下:
SQL_NO_CACHE means that thewww.diuxie.com query result is not cached. It does not meanthat the cache is not used to answer the query.
You may use RESET QUERY CACHE to remove all queries from the cache and then your next query should be slow again. Same effect if you change
the table, because this makes all cached queries invalid.
mysql> select count(*) from users where email = 'hello';
| count(*) |
| 0 |
1 row in set (7.22 sec)
mysql> select count(*) from users where email = 'hello';
| count(*) |
| 0 |
1 row in set (0.45 sec)
mysql> select count(*) from users where email = 'hello';
| count(*) |
| 0 |
1 row in set (0.45 sec)
mysql> select SQL_NO_CACHE count(*) from users where email = 'hello';
| count(*) |
| 0 |
【如何使用MYSQL语句进行数据缓存()】1 row in set (0.43 sec)

    推荐阅读