从两个表中获取最高总和值

时间:2012-12-29 14:25:31

标签: php mysql html-table

这是我的代码:

$query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
$result = mysql_query(query1);
$row_query1 = mysql_fech_assoc($result);

do{
    $user = $row_query1['user'];
    $query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
    $result2 = mysql_query($query2);
    $row_query2 = mysql_fetch_assoc($result2);
    $sum = $row_query1['total1'] + $row_query2['total1'];
    <tr> <?php echo $sum; ?></tr>
}while($row_query1 = mysql_fech_assoc($result));

我需要从这个循环中获得$ sum的最高值。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

你可以这样做..拿一个临时变量($ temp),它可以检查sum变量($ sum)。

     $query1 = "select user, sum(column) as total1 from table1 GROUP BY user";
     $result = mysql_query(query1);
     $row_query1 = mysql_fech_assoc($result);
     $temp = 0;

    do{

    $user = $row_query1['user'];

    $query2 = "select names, sum(column1) as total2 from table2 WHERE names ='$user' GROUP BY names";
    $result2 = mysql_query($query2);
    $row_query2 = mysql_fetch_assoc($result2);

    $sum = $row_query1['total1'] + $row_query2['total1'];

    if($temp < $sum)
    $temp = sum;

    echo "<tr>$sum</tr>";

   }while($row_query1 = mysql_fech_assoc($result));
   echo "maximum sum :".$temp;

答案 1 :(得分:0)

我建议做一个JOIN而不是自己执行子查询:

select user, sum(column) + sum(column1) as total
from table1 
INNER JOIN table2 ON names = user
GROUP BY user

其余部分在代码中应该是直截了当的。