簡體   English   中英

MySQL的左外連接問題

[英]Left outer join issue with 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

我猜你的問題是:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM