简体   繁体   English

缓存mysql查询结果?

[英]cache mysql query result?

I use a several mysql queries on a page to fetch data from multiple tables using mysqli prepare statements. 我在页面上使用几个mysql查询来使用mysqli prepare语句从多个表中获取数据。

Lets say i have like 20 queries from database tables on a page. 让我说我有一个页面上数据库表的20个查询。 Since there are so many queries, I would like to improve the performance by storing the results in cache for some minutes? 由于查询太多,我想通过将结果存储在缓存中几分钟来提高性能? Is it good idea? 这是好主意吗? If yes, how I can store the results using cache for the , for example, following query? 如果是,我如何使用缓存存储结果,例如,以下查询?

$city = "Amersfoort";

if ($stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?")) {
    $stmt->bind_param("s", $city);
    $stmt->execute();
    $stmt->bind_result($district);
    $stmt->fetch();
    printf("%s is in district %s\n", $city, $district);
    $stmt->close();
}

Thanks. 谢谢。

If the SQL statements are cheap in processing, you probably don't need to cache them. 如果SQL语句在处理上很便宜,那么您可能不需要缓存它们。 If they require hefty calculations or run on really large datasets, you might need a cache. 如果它们需要大量计算或在非常大的数据集上运行,则可能需要缓存。 Remember that the cache needs to be faster than the SQL query. 请记住,缓存需要比SQL查询更快。

There are several ways to cache in PHP: 有几种方法可以在PHP中缓存:

  • File cache, serialzing the data and storing it into a file named like the hash of the query. 文件缓存,序列化数据并将其存储到名为查询哈希的文件中。 Remember that getting cache lifetime, concurrent accesses and so is hard -so consider using a library that does it, ie with PEAR's Cache or Cache_Lite 请记住,获取缓存生存期,并发访问等都很难 - 考虑使用执行它的库,即使用PEAR的CacheCache_Lite
  • memcached memcached的
  • shared memory as cache, ie by using APC functions like apc_add 共享内存作为缓存,即使用apc_add等APC函数

You also might want to cache the complete page or parts of the page instead of single queries. 您还可能希望缓存整个页面或页面的一部分而不是单个查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM