从foreach循环内的Mysql查询创建数组

时间:2012-08-31 16:34:30

标签: php mysql arrays

我正在尝试填充显示统计信息的表格。我已使用以下查询将广告系列ID列表放入数组中:

$query = "SELECT `id` FROM `c_templates` ORDER BY `id`";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
    $id[] = $row['id'];
}

一旦我拥有了所有的id,我使用foreach循环为每个id收集所有表数据进行5次查询。

foreach($id as $i){
    // sent
    $query = "SELECT `template`, COUNT(*) as count FROM `s_log` WHERE `template` = '".$i."' AND `time_sent` BETWEEN '".$start."' AND '".$stop."'";
    $result = mysql_query($query) or die(mysql_error());
    while($row = mysql_fetch_array($result)){
        $template[] = $row['template'];
        $count[] = $row['count'];
    }

    // opens
    $query = "SELECT COUNT(*) as count FROM `t_opens` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."'";
    $result = mysql_query($query) or die(mysql_error());
    while($row = mysql_fetch_array($result)){
        $opens[] = $row['count'];
    }

    // clicks   
    $query = "SELECT `campaign_id`, COUNT(*) as count FROM `t_analytics` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."'";
    $result = mysql_query($query) or die(mysql_error());
    while($row = mysql_fetch_array($result)){
        $click_count[] = $row['count'];
    }

    // conversions
    $query = "SELECT `conversion_value`, COUNT(*) as count FROM `t_analytics` WHERE `campaign_id` = '".$i."' AND `timestamp` BETWEEN '".$start."' AND '".$stop."' AND `conversion_value` > 0";
    $result = mysql_query($query) or die(mysql_error());
    while($row = mysql_fetch_array($result)){
        $conversion_value[] = $row['conversion_value'];
        $conversion_count[] = $row['count'];
    }

    // bounce rate
    $query = "SELECT COUNT(*) AS `ck` FROM `s_log` WHERE `time_sent` BETWEEN '".$start."' AND '".$stop."' AND `status` = 'hardbounce' OR `status` = 'softbounce' AND `template` = '".$i."'";
    $result = mysql_query($query) or die(mysql_error());
    while($row = mysql_fetch_array($result)){
        $bounce_count[] = $row['ck'];
    }
}

问题是此过程需要4-5秒才能执行超过40-50 id条记录。我在每次查询后放置了一些计时器,以确认查询是否正确执行了。我运行了OPTIMIZE并进行了双重检查以确保所有内容都已正确编入索引。据我所知,问题不在于mysql。

我唯一能找到的是每个循环周期后延迟.1.5秒。当试图运行40-50行时,这肯定会开始累加起来。

我的问题:是否有更好,更快的方法来获取此数据?还有什么我应该检查以加快这个过程吗?

我能想到的唯一解决方案是为每个统计信息(总共5个查询)运行一个查询,获取所有id的数据,并将它们放在一个数组中以便以后显示。我不确定如何做到这一点,或者甚至可能。在我看来,我必须为每个id运行一个单独的查询,但我希望我错了。

任何帮助将不胜感激!!

0 个答案:

没有答案