简体   繁体   中英

Get highest sum value from two tables

Here is my code:

$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));

I need to get the highest value of $sum from this loop. Can anyone help?

You can do like this.. take a temporary variable($temp) which can have check upon the sum variable($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;

I would advice doing a JOIN instead of performing the sub queries yourself:

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

The rest should be straightforward in code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM