【问题标题】:Cache results of a mysql query manually to a txt file将mysql查询的结果手动缓存到txt文件
【发布时间】:2010-09-11 18:43:12
【问题描述】:

有没有办法将mysql查询的结果手动缓存到txt文件?

例如:

$a=1;
$b=9;
$c=0;
$cache_filename = 'cached_results/'.md5("$a,$b,$c").'.txt';
if(!file_exists($cache_filename)){
    $result = mysql_query("SELECT * FROM abc,def WHERE a=$a AND b=$b AND c=$c");
    while($row = mysql_fetch_array($result)){
        echo $row['name'];
    }
    // Write results on $row to the txt file for re-use
}else{
    // Load results just like $row = mysql_fetch_array($result); from the txt file
}

原始查询包含更多使用多个表的 WHERE 和连接。 那么,这可能吗?如果有,请解释一下。

谢谢你, pnm123

【问题讨论】:

  • 除非您的实际查询非常复杂并且索引不是很好,否则我认为您的缓存会更慢。请记住,在最坏的情况下,mySQL 也会从文件系统中获取结果。
  • 我已索引所有必填字段。所以我认为通过缓存查询结果会更快,因为 MySQL 只需要运行一次,因为查询没有变化。
  • Mysql 有自己的查询缓存。处理查询是 Mysql 的工作。而过早的优化是万恶之源。
  • 但有时我们可以比现在的方式做得更好。

标签: php mysql caching


【解决方案1】:

如果您确定您的数据有很长的生存时间,您当然可以通过将数据临时保存到文本文件来缓存数据。

if (!file_exists($cachefile)) {
    // Save to cache
    $query=mysql_query('SELECT * FROM ...');
    while ($row=mysql_fetch_array($query))
        $result[]=$row;
    file_put_contents($cachefile,serialize($result),LOCK_EX);
}
else
    // Retrieve from cache
    $result=unserialize(file_get_contents($cachefile));
foreach ($result as $row)
    echo $row['name'];

虽然如果考虑性能,使用 APC、MemCache 或 XCache 会是更好的选择。

【讨论】:

  • 如果有两行或更多行/结果怎么办?我需要改用什么 while($row=mysql_feth_array($result)){ ?
  • 然后使用serialize($row)而不是serialize($result)
  • 对不起。我仍然没有从缓存中检索的方式。顺便说一句,我已经编辑了这个问题。那么,如何通过从缓存中检索数据来打印多个结果?就像 while(){ echo; }
猜你喜欢
  • 2014-02-20
  • 2016-09-07
  • 2015-07-04
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多