将GROUP BY结果作为分离的变量返回

时间:2012-05-04 22:05:37

标签: php mysql

我是mysql / php的新手,我正在尝试使用

构建自定义查询
$query = "SELECT expo_location,  SUM(total_sale) FROM _sales_db WHERE day IN('Friday') GROUP BY expo_location"; 

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

// Print out result
while($row = mysql_fetch_array($result)){
  echo "<span style='font-weight:normal;color:#cfcfcf;'>"."Total ". $row['expo_location']. " = $". number_format((float)$row['SUM(total_sale)'], 2, '.', '')."</span>";
  echo "<br />";
}

返回:

//
Total Canton = $295.94
Total Malone = $980.24
Total Massena = $1187.10
//

我希望只使用GROUP BY将“expo_location”名称作为变量返回。

Example
$Canton = 
$Malone = 
$Massena =

总而言之,将所有条目放在一列并将它们组合在一起并将它们作为变量返回?

2 个答案:

答案 0 :(得分:2)

下面的代码将为您创建一个关联数组,以便您可以执行类似$ expo_locations ['Canton']的操作,其中包含295.94

    $query = "SELECT expo_location,  SUM(total_sale) FROM _sales_db WHERE day IN('Friday') GROUP BY expo_location"; 

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

    $expo_locations = array();

    // Print out result
    while($row = mysql_fetch_array($result)){
        $expo_locations[$row['expo_location']] = number_format((float)$row['SUM(total_sale)'], 2, '.', '');
    }

答案 1 :(得分:1)

您可以在执行记录循环时将提取的位置数据存储在数组中,然后简单地将所有收集的数据压缩到字符串中。

$query = "SELECT expo_location,  SUM(total_sale) FROM _sales_db WHERE day IN('Friday') GROUP BY expo_location"; 

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

$locations = array();

// Print out result
while($row = mysql_fetch_array($result)){
    $locations[] = $row['expo_location'];
}

$locations_string = implode(', ', $locations); // String version
var_dump($locations); // Displays array content.