2014-09-03 63 views
0

所以我有2个表。一张表具有所有实际的campaign_id信息。 第二个表有关于campaign_id的印象/统计信息MySQL + PHP数百万行,对来自多个查询的数据进行排序。内存消耗

我在页面上有一个表格(我使用ajax,但除此之外)。我想“排序”一列,但所有行都是由campaign_id表生成的,我首先运行所有广告系列的所有统计信息,然后将它们链接到每行。那么在所有的信息/数据结束之后,它会将其全部分类。这使用了大量的内存和资源。 这是否有效?有没有更好的解决方案来分拣大量的数据?

// I have to increase memory because the sorting takes a lot of resource 
ini_set('memory_limit','1028M'); 

// the column I want to sort 
$sortcolumn = $this->input->post('sortcolumn'); 
// direction of the sort ASC/DESC 
$sortby = $this->input->post('sortby'); 

// millions of impression data that is linked with campaign_id 
$cdata= array(); 
$s = "SELECT report_campaign_id,"; 
$s .= "SUM(report_imps) AS imps "; 
$s .= "FROM Campaign_Impressions"; 
$s .= "GROUP BY report_campaign_id "; 
$r = $this->Qcache->result($s,0,'campaignsql'); 
foreach($r as $c) { 

    $cdata[$c->report_campaign_id]['imps'] = ($c->imps) ? $c->imps : 0; 
} 


// 500,000+ thousand campaigns 
// I draw my table from these campaigns 
$rows = array(); 
$s = "SELECT * FROM Campaigns "; 
$r = $this->db->query($s)->result(); 
foreach($r as $c) 
{ 
    $row= array(); 
    $row['campaign_id'] = $c->campaign_id; 
    // other campaign info here... 

    // campaign statistics here... 
    $row['campaign_imps'] = $cdata[$c->campaign_id]['imps']; 

    // table row 
    $rows[] = $row; 
} 


// prepare the columns i want to sort 
$sortc = array(); 
foreach($rows as $sortarray) { 
    if (!isset($sortarray[ $sortcolumn ])) continue; 
    $sortc[] = str_replace(array('$',','),'',$sortarray[ $sortcolumn ]); 
} 

// sort columns and direction 
array_multisort($sortc,(($sortby==='asc')?SORT_ASC:SORT_DESC),SORT_NATURAL,$rows); 

正如你所看到的,“campaign_impressions”表运行数据对“天天”的活动,似乎并没有那么高效,但更有效的运行,而不是每行一个查询就知道这些数据。

(我不显示所有的活动,但我需要运行他们每个人知道所有的排序)

+1

在单个查询中加入Campaign_Impressions和Campaigns,允许您在查询中指定ORDER BY子句 – 2014-09-03 15:44:53

+0

不,效率不高:您正在有效地复制从MySQL到PHP的数据并进行处理。最好将所有排序和分组推入SQL,理想的情况是提前进行分页或过滤,以便在适当的情况下限制范围。考虑'加入'的印象,'限制'提供分页。如果你必须用PHP来做,可以考虑使用yield来限制中间映射的效果。 – bishop 2014-09-03 15:45:52

+0

定义“巨大”。通常,如果您没有索引,则排序效率低下,但在临时文件中完成排序以最大限度地减少内存影响。如果你的MySQL服务器使用了过多的内存,它的配置不正确。 – tadman 2014-09-03 15:52:24

回答

0

你应该让MySQL的做的工作我使用order by

如果这仍需要MySQL方面的很多时间考虑在列上使用排序索引