MySQL通过左联接获得总和

时间:2019-04-04 09:34:03

标签: mysql left-join

我有三个桌子。

  1. 地区
  2. 美食
  3. 横幅

如果我运行此查询

SELECT SUM(fee) FROM BANNERS;

输出将为10,000

如果我运行此查询

SELECT SUM(fee) FROM CUISINE;

输出将为12,800

但是如果我运行此查询

SELECT REGIONS.name,
sum(BANNERS.fee) as banner_revenue,
sum(CUISINE.fee) as cuisine_revenue
FROM REGIONS
LEFT JOIN BANNERS ON REGIONS.id = BANNERS.region_id
LEFT JOIN CUISINE ON REGIONS.id = CUISINE.region_id
GROUP BY REGIONS.name;

输出错误。我想要的输出是

name    | banner_revenue | cuisine_revenue
------------------------------------------
NY      | 10,000         | 4,800
Paris   | NULL           | 8,000
London  | NULL           | NULL

patch which is provided for TYPO3 8.7

为什么会发生这种情况? 请参考我的数据库小提琴。

2 个答案:

答案 0 :(得分:1)

如果您运行

SELECT *
       FROM REGIONS
            LEFT JOIN BANNERS
                      ON REGIONS.id = BANNERS.region_id
            LEFT JOIN CUISINE
                      ON REGIONS.id = CUISINE.region_id;

您会注意到,对于每个区域横幅对,所有的cusine都被加入,从而使cuisins“相乘”。即他们的费用也成倍增加。

在派生表中进行分组,然后将它们加入以获得所需的结果。

SELECT r.name,
       sb.fee,
       sc.fee
       FROM REGIONS r
            LEFT JOIN (SELECT sum(b.fee) fee,
                              b.region_id
                              FROM BANNERS b
                              GROUP BY b.region_id) sb
                      ON sb.region_id = r.id
            LEFT JOIN (SELECT sum(c.fee) fee,
                              c.region_id
                              FROM CUISINE c
                              GROUP BY c.region_id) sc
                      ON sc.region_id = r.id;

答案 1 :(得分:0)

请考虑以下内容:

SELECT r.name
     , x.header
     , x.fee 
  FROM REGIONS r
  LEFT 
  JOIN 
     ( SELECT 'banner' header, region_id, fee FROM banners
       UNION
       SELECT 'cuisine', region_id, fee FROM cuisine
     ) x
    ON x.region_id = r.id 
 ORDER  
    BY r.name;


    +--------+---------+------+
    | name   | header  | fee  |
    +--------+---------+------+
    | London | NULL    | NULL |
    | NY     | cuisine | 2500 |
    | NY     | cuisine | 2300 |
    | NY     | banner  | 2000 |
    | NY     | banner  | 5000 |
    | NY     | banner  | 3000 |
    | Paris  | cuisine | 8000 |
    +--------+---------+------+