Mysql离开了join,sum和group_by

时间:2016-12-20 05:39:52

标签: mysql left-join

我有4张桌子。 区域土地住宅商品

  • land 有一对一的rels。 区域
  • land 拥有一对多的rels。 house
  • house 拥有一对多的rels。 商品

a busy cat

sqlfiddle http://sqlfiddle.com/#!9/5eaec

当前查询

SELECT
    Sum(land.wide) AS land_wide,
    Sum(house.price) AS house_price,
    Sum(goods.amount) AS goods_amount,
    Sum(goods.price) AS goods_price,
    region.region_name
FROM
    land
LEFT JOIN house ON house.land_id = land.id
LEFT JOIN goods ON goods.house_id = house.id
LEFT JOIN region ON land.region_id = region.id
GROUP BY
    region.region_name
ORDER BY
    region.id ASC

但不能按预期工作。

所需的输出

+-----------+-------------+-------------+--------------+---------+
| land_wide | house_price | goods_price | goods_amount | region  |
+-----------+-------------+-------------+--------------+---------+
| 510       | 57910       | 1900        | 56           | Tokyo   |
|           |             |             |              | Osaka   |
|           |             |             |              | Nagoya  |
|           |             |             |              | Sapporo |
+-----------+-------------+-------------+--------------+---------+

有人会给我一个有帮助的解决方案吗?我很确定它可以在SQL中完成吗?

2 个答案:

答案 0 :(得分:1)

SELECT 
   land_wides.land_wide, 
   house_prices.house_price, 
   goods_amounts_prices.goods_price, 
   goods_amounts_prices.goods_amount, 
   region.region_name
FROM region
LEFT JOIN (SELECT
              Sum(land.wide) AS land_wide,
              region.id AS region_id
           FROM region
           LEFT JOIN land ON land.region_id = region.id
           GROUP BY region.id) land_wides ON region.id = land_wides.region_id
LEFT JOIN (SELECT
              Sum(house.price) AS house_price,
              region.id AS region_id
           FROM region
           LEFT JOIN land ON land.region_id = region.id
           LEFT JOIN house ON house.land_id = land.id
           GROUP BY region.id) house_prices ON region.id = house_prices.region_id
LEFT JOIN (SELECT
              Sum(goods.amount) AS goods_amount,
              Sum(goods.price) AS goods_price,
              region.id AS region_id
           FROM region
           LEFT JOIN land ON land.region_id = region.id
           LEFT JOIN house ON house.land_id = land.id
           LEFT JOIN goods ON goods.house_id = house.id
           GROUP BY region.id) goods_amounts_prices on goods_amounts_prices.region_id = region.id
ORDER BY region.id

答案 1 :(得分:0)

左连接应该是内连接。您希望对匹配的行进行分组。不是不匹配的行,因此对总和进行分组。