MySQL连接具有重复索引值的表

时间:2017-11-23 12:13:07

标签: mysql join

我们有两个MySQL表,当使用标准连接加入时会产生重复的结果。原因是用于连接它们的公共字段不是唯一的。我们尝试了多种变体,但无法获得正确的结果。希望有人可以指出我们正确的方向。

Table A / ws_511_1

Table B / ws_583_1

正确的输出应如下所示:

Correct output

使我们最接近正确输出的查询(此处未包括所有列):

SELECT a.col_3 AS Data, SUM(a.col_4) AS `October 2016`, SUM(a.col_5) AS `November 2016`, SUM(b.col_4) AS `February 2017`, SUM(b.col_5) AS `March 2017` FROM ws_511_1 a LEFT JOIN (SELECT * FROM ws_583_1 b GROUP BY col_3) b ON b.col_3 = a.col_3 WHERE a.id!='1' GROUP BY a.col_3

此查询的输出是:

Incorrect output

您会注意到10月和11月是正确的,但加入的列结果不正确。

1 个答案:

答案 0 :(得分:0)

您可以使用左表格的结果组

  SELECT  a.col_3 AS Data
    , SUM(a.col_4) AS `October 2016`
    , SUM(a.col_5) AS `November 2016`
    , b.`February 2017`
    , b.`March 2017` 
  FROM ws_511_1 a 
  LEFT JOIN (
        SELECT col_3
        , SUM(b.col_4) AS `February 2017`
        , SUM(b.col_5) AS `March 2017`  
        FROM ws_583_1 b 
        GROUP BY col_3
  ) b ON b.col_3 = a.col_3 
  WHERE a.id!='1' 
  GROUP BY a.col_3 , , b.`February 2017`, b.`March 2017`