我有一个大型数据库,其中包含 1500 人的实验结果。每个人有 96 个数据点。我写了下面的脚本来总结然后格式化数据,以便分析软件使用。起初一切都很好,直到我有超过 500 个人。现在我的内存用完了。
我想知道现在是否有人建议在不牺牲速度的情况下克服内存限制问题。
数据库中的表是这样的
fishId assayId 等位基因 1 等位基因 2
14_1_1 1 A T
14_1_1 2 A A
$mysql = new PDO('mysql:host=localhost; dbname=aquatech_DB', $db_user, $db_pass);
$query = $mysql->prepare("SELECT genotyped.fishid, genotyped.assayid, genotyped.allele1, genotyped.allele2, fishId.sex, " .
"fishId.role FROM `fishId` INNER JOIN genotyped ON genotyped.fishid=fishId.catId WHERE fishId.projectid=:project");
$query->bindParam(':project', $project, PDO::PARAM_INT);
$query->execute();
所以这是对数据库的调用。它连接来自两个表的信息来构建我需要的文件。
if(!$query){
$error = $query->errorInfo();
print_r($error);
} else {
$data = array();
$rows = array();
if($results = $query->fetchAll()){
foreach($results as $row)
{
$rows[] = $row[0];
$role[$row[0]] = $row[5];
$data[$row[0]][$row[1]]['alelleY'] = $row[2];
$data[$row[0]][$row[1]]['alelleX'] = $row[3];
}
$rows = array_unique($rows);
foreach($rows as $ids)
{
$col2 = $role[$ids];
$alelleX = $alelleY = $content = "";
foreach($snp as $loci)
{
$alelleY = convertAllele($data[$ids][$loci]['alelleY']);
$alelleX = convertAllele($data[$ids][$loci]['alelleX']);
$content .= "$alelleY\t$alelleX\t";
}
$body .= "$ids\t$col2\t" . substr($content, 0, -1) . "\n";
这会解析数据。在我需要的文件中,每个人必须有一行,而不是每个人有 96 行,这就是必须格式化数据的原因。在脚本的末尾,我只是将 $body 写入文件。
我需要输出文件是
FishId 检测 1 检测 2
14_1_1 A T A A
$location = "results/" . "$filename" . "_result.txt";
$fh = fopen("$location", 'w') or die ("Could not create destination file");
if(fwrite($fh, $body))
最佳答案
与其使用 fetchAll() 将数据库查询的整个结果读取到一个变量中,不如逐行获取它:
while($row = $query->fetch()) { ... }
关于php - 使用有限的内存处理来自 mysql 的大型结果集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23805071/