从MySQL查询返回的组结果

时间:2016-09-05 15:41:55

标签: php mysql

我正在查询由前员工构建的数据库,非常糟糕!我已成功收集并输出了我需要的所有数据 - 但我想将数据分组到问题编号。

目前输出是这样的......

Company 1
Issue number: 142
Total: 480.00

Company 2
Issue number: 142
Total: 46

Company 3
Issue number: 142
Total: 240.00

Company 4
Issue number: 142
Total: 420.00

Company 5
Issue number: 142
Total: 468.00

Company 6
Issue number: 142
Total: 252.00

我希望它像......一样阅读。

**Issue number: 142**
Company 1 Total 480
Company 2 Total 468
etc etc I.e grouping them into issue numbers. 

这是我的代码......

$sql = "
SELECT bf_total_cost
     , bf_date_added
     , ib_issue_number
     , companyname
     , contacts_id
     , bf_id
     , bf_company_id
     , ib_booking_form_number 
  FROM contacts
     , booking_form
     , issues_booked 
 WHERE ib_issue_number >= 141 
   AND ib_issue_number <= 165 
   AND bf_date_added >= '2014-11-01' 
   AND bf_date_added <= '2016-08-31' 
   AND contacts_id = bf_company_id 
   AND bf_id = ib_booking_form_number 
 ORDER 
    BY ib_issue_number ASC;
";

$result = mysql_query($sql) or die (mysql_error());

$row = mysql_fetch_array($result) or die (mysql_error());
while($row = mysql_fetch_array($result)) {

echo '<ul>';
echo '<li>'.$row['companyname'] .'</li>';
echo '<li>'.$row['ib_issue_number'] .'</li>';
echo '<li>'.$row['bf_total_cost'] .'</li>';
echo '</ul>';
}

2 个答案:

答案 0 :(得分:0)

在MySQL中使用聚合:

 SELECT sum(bf_total_cost) ... GROUP BY ib_issue_number, bf_company_id

这将按行号和公司ID对每一行进行分组。然后sum()将返回每个分组的总成本。

如果您只想按问题编号分组,请从组中删除bf_company_id。

答案 1 :(得分:0)

您可以在从结果中获取行时在while循环中创建嵌套/分组数组:

$result = mysql_query($sql) or die (mysql_error());

$groupedArray = array();
while($row = mysql_fetch_assoc($result)) {
    $groupedArray[$row['ib_issue_number']][] = $row;
}

然后,您可以将其输出为嵌套的HTML列表:

echo "<ul>";
foreach ($groupedArray as $issueNumber => $group) {
    echo "<li>issue number: $issueNumber <ul>";
    foreach ($group as $row) {
        echo "<li>Company: {$row['companyname']}; Total {$row['bf_total_cost']}</li>";
    }
    echo "</ul></li>";
}
echo "</ul>";