0

我在下面有这段代码,我首先从表用户中选择所有 id,然后从优惠券表中选择并找到属于该用户的总积分,然后我还从零售商那里选择属于该用户的所有积分桌子。然后我计算这些总和之间的差值。

但是出了点问题,我得到了完全不同的观点。

$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>";
}

输出样本:

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

1 回答 1

0

我猜你的问题是:

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

$total1$total为所有用户附加所有记录。我认为应该是:

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

试试这个:

 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;
于 2012-11-15T08:29:10.700 回答