php - 使用有限的内存处理来自 mysql 的大型结果集

标签 php mysql performance memory pdo

我有一个大型数据库,其中包含 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/

相关文章:

php - Codeigniter 3 - session 不工作

php - 将行添加到 html 表格

mysql - 在 MySql 中执行更新命令,同时覆盖 sql_safe_updates 选项

mysql - 我怎样才能结合这个 INSERT 和 SELECT MySQL 语句?

linux - 为什么我的 linux 熵有这么低的上限?

python - 运行时间 : Does Print Count as a Step?

php - 有什么方法可以在我的 Web 应用程序中提供不同的视频质量,而无需将每个视频转换为每种格式?

c# - 如何在 C#.NET、PHP 和 MySQL 之间获得通用的编码?

angularjs - 与 DOM 中 ng-app/ng-controller 放置相关的 Angular View 性能