SQL左外连接的意外输出

时间:2012-10-27 00:15:48

标签: mysql sql

我有这些表, rollsrollsout。我想执行左外连接。

          |type|height|weight|Rate|
          -------------------------
          |RP  |2ft   | 200  | 100|
          |RP  |2ft   | 200  | 100|
          |RP  |2ft   | 200  | 100|
          |LD  |2ft   | 100  | 130|

rollsout

          |type|height|weight|Rate|
          -------------------------
          |RP  |2ft   | 200  | 100|
          |RP  |2ft   | 200  | 100|

SUMing,JOINing和GROUPings ==>

之后的预期输出
          |type|height|SUM(rolls.weight)|SUM(rollsout.weight)|
          ----------------------------------------------------
          |RP  |2ft   | 600             | 400                |
          |LD  |2ft   | 100             | NILL               |

我的代码:

 SELECT rolls.hight,rolls.type,SUM(rolls.weight),SUM(rollsout.weight)
 FROM rolls 
 LEFT OUTER JOIN rollsout 
 ON rolls.hight = rollsout.hight AND rolls.type= rollsout.type 
 GROUP BY rolls.hight,rolls.type

但上述代码的O / P是

          |type|height|SUM(rolls.weight)|SUM(rollsout.weight)|
          ----------------------------------------------------
          |RP  |2ft   | 1200            | 1200               |
          |LD  |2ft   | 100             | NILL               |

我不知道我哪里出错了 - 你能解释一下吗?

2 个答案:

答案 0 :(得分:3)

你没有做错任何事。这是JOINs的行为

它是左边的行数X右边的行数,在你的情况下,它是3 x 2 = 6.而且6 x 200 = 1200

试试这个

Select rolls.height,rolls.type, SUM(rolls.weight) as W, rollsout.Ww
 FROM rolls 
 LEFT JOIN
       (Select height,type, SUM(weight) as Ww 
         From rollsout GROUP BY height, type
       ) as rollsout
ON rolls.height = rollsout.height AND 
rolls.type= rollsout.type 
GROUP BY rolls.height,rolls.type

SQLFiddle

我知道这在SQL Server中不起作用,但它适用于MySQL

答案 1 :(得分:0)

它将Rollsout中每行的所有Rolls与RP类型相加。您需要从rollout获取不同的行:

SELECT rolls.hight,rolls.type,SUM(rolls.weight),SUM(R2.weight)
 FROM rolls 
 LEFT OUTER JOIN (SELECT DISTINCT * FROM rollsout) AS R2 ON  
 ON rolls.hight = R2.hight AND rolls.type= R2.type 
 GROUP BY rolls.hight,rolls.type