简体   繁体   中英

Left outer join issue with mysql

I have this code below, with which I select first all id's from table users then I select and find the total sum of points from the coupon table which belong to this user, then I also select all points that belong to this user from the retailer table. Then I do the difference between this sums.

But something is going wrong, I get completely different points.

$query4 = 'SELECT u.*, sum(c.points) as total_sum1, sum(r.basket_value) as total_sum 
           FROM users u 
           left outer join coupon c on u.user_id=c.user_id
           left outer join retailer r on u.user_id=r.user_id 
           group by user_id';
$result4 = mysql_query($query4) or die(mysql_error());

$total1=0;
$total=0;
$total2=0;
while($row = mysql_fetch_array($result4)) {
    $total1 += $row['total_sum1'];
    $total += $row['total_sum'];
    echo "<table>";
    echo "<tr>";
    echo "<td>";
    echo  $total2=$total-$total1;
    echo "</td>";
    echo "<td>";

    echo "</td>";
    echo "</tr>";
    echo "</table>";
}

Sample of the output:

total points remaining    |   user_id
0                             9839467227
0                             9853125067
0                             9937770769
0                             9974837329
222060                        A101
0                             A102
0                             A103
0                             A104

I guess your problem is:

    $total1 += $row['total_sum1'];
    $total += $row['total_sum'];

$total1 and $total is appending all record for all user. I think it must be:

    $total1 = $row['total_sum1'];
    $total = $row['total_sum'];

Try this:

 SELECT u.*, SUM(c.ts) AS total_sum1, SUM(r.bv) AS total_sum 
FROM users u 
LEFT JOIN 
 (SELECT user_id ,SUM(points) AS ts FROM coupon GROUP BY user_id) c 
 ON u.user_id=c.user_id 
LEFT JOIN 
 (SELECT user_id ,SUM(basket_value) AS bv FROM retailer GROUP BY user_id) r 
ON u.user_id=r.user_id 
GROUP BY u.user_id;

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