天天看點

如何使用MYSQL語句進行資料緩存?

查詢緩存設定

1) 驗證伺服器是否支援查詢緩存

show variables like '%have_query_cache%';

| variable_name | value |

| have_query_cache | yes |

2) 查詢緩存會受到以下3個系統變量值的影響

show variables like 'query_cache%';

| 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查詢總是會使用查詢緩存,如果緩存沒有命中則開始查詢的執行計劃到表中查詢資料。

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)

1 row in set (0.45 sec)

mysql> select sql_no_cache count(*) from users where email = 'hello';

1 row in set (0.43 sec)

繼續閱讀