LEFT OUTER JOIN SUM加倍问题

时间:2011-01-09 14:36:57

标签: php 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

我只是不知道如何解决这个问题。

3 个答案:

答案 0 :(得分:3)

问题在于您构建了两个表的叉积,它将结果乘以相对表中的行数。要解决此问题,首先要计算聚合派生表中某个表的结果,然后将此聚合结果连接到另一个表。

SELECT
    shop_name,
    shoptime,
    IFNULL(SUM(banana_amount), 0)
FROM (
    SELECT shop_name, SUM(shop_time) as shoptime
    FROM shopping
    GROUP BY shop_name
) tt
LEFT JOIN bananas tz ON tt.shop_name=tz.banana_person
GROUP BY shop_name

答案 1 :(得分:1)

使用*是问题(因为您正在使用分组依据)。 此外,SUM(shop_time)在banaanas中被乘以多少行,因此你得到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; 

答案 2 :(得分:1)

select
      xx.shop_name
    , xx.tot_time
    , coalesce(yy.tot_bananas, 0) as tot_bananas
from
(
    select
          shop_name
        , sum(shop_time) as tot_time
    from shopping
    group by shop_name
) as xx
left join
(
    select
          banana_person
        , sum(banana_amount) as tot_bananas
    from bananas
    group by banana_amount
) as yy on xx.shop_name = yy.banana_person
order by xx.shop_name
;