mysql的左外连接问题

时间:2012-11-15 08:13:15

标签: php mysql

我在下面有这个代码,我首先从表用户中选择所有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

1 个答案:

答案 0 :(得分: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;