一尘不染

左外连接总和成倍增加问题

sql

表:购物

shop_id shop_name  shop_time
1   Brian  40
2   Brian   31
3   Tom   20
4   Brian   30

桌子:香蕉

banana_id  banana_amount  banana_person
1    1     Brian
2    1     Brian

我现在要打印:

姓名:汤姆| 时间:20 | 香蕉:0
名称:Brian | 时间:101 | 香蕉2

我使用了以下代码:

$result = dbquery("SELECT tz.*, tt.*,
SUM(shop_time) as shoptime,
count(banana_amount) as bananas

 FROM shopping tt
 LEFT OUTER JOIN bananas tz ON tt.shop_name=tz.banana_person
 GROUP by banana_person
LIMIT 40
");



while ($data5 = dbarray($result)) {

echo 'Name: '.$data5["shop_name"].' | Time: '.$data5["shoptime"].' | Bananas: '.$data5["bananas"].'<br>';


}

问题是我得到了这个:

姓名:汤姆| 时间:20 | 香蕉:0
名称:Brian | 时间:202 | 香蕉6

我只是不知道该如何解决。


阅读 169

收藏
2021-03-08

共1个答案

一尘不染

问题是使用*(因为您正在使用分组依据)。另外,SUM(shop_time)被乘以香蕉中的尽可能多的行,因此得到202(香蕉中的两行)

试试这个查询:

SELECT tt.shop_name, 
           SUM(shop_time)           AS shoptime, 
           Ifnull(banana_amount, 0) AS bananas 
    FROM   shop tt 
           LEFT OUTER JOIN (SELECT banana_person, 
                                   SUM(banana_amount) AS banana_amount 
                            FROM   bananas 
                            GROUP  BY banana_person) tz 
             ON tt.shop_name = tz.banana_person 
    GROUP  BY shop_name;
2021-03-08