如何联接两个表并基于不同的列在Mysql中汇总它们的列

时间:2019-01-04 22:06:49

标签: mysql join outer-join

我通过regNo列连接两个表。我想在RegNo匹配的地方添加Table1.points和Table2.points的点,以防万一它不匹配,我也希望将它的点包括在列表中,如下图所示 expected results From the two table1& table2

我已经阅读了存在的问题,但没有找到解决方法,例如How can I sum columns across multiple tables in MySQL?

(
    SELECT `Ex`.regNo,(`In`.`points`+`Ex`.`points`) AS 'Points' 
    FROM Table1`In` 
    LEFT JOIN Table2`Ex` ON `In`.`regNo` = `In`.`regNo`
)
UNION
(
    SELECT`Ex`.regNo,(`In`.`points`+`Ex`.`points`) AS 'Points' 
    FROM Table1`In` 
    RIGHT JOIN Table2`Ex` ON `In`.`regNo` = `In`.`regNo`
);

我希望它给出按唯一(DISTINCT)regNo排列的列表

3 个答案:

答案 0 :(得分:1)

您需要UNION后跟GRoUP BY

SELECT regNo, SUM(points) AS total
FROM (
    SELECT regNo, points
    FROM Table1

    UNION ALL

    SELECT regNo, points
    FROM Table2
) AS u
GROUP BY regNo

答案 1 :(得分:0)

您正在寻找两个表之间的FULL JOIN

SELECT 
    COALESCE(t1.id, t2.id) id
    COALESCE(t1.regNo, t2.regNo) regNo
    COALESCE(t1.points, 0) +  COALESCE(t2.points 0) points
FROM
    table1 t1
    FULL JOIN table2 t2 on t1.regNo = t2.regNo

NB:您没有指定生成新id的期望操作,因此默认情况下,上述查询将显示table1.id(如果可用),否则显示table2.id

如果您最好生成一个新的,自动递增的字段,则:

SET @i=0;
SELECT 
    @i:=@i+1 id
    COALESCE(t1.regNo, t2.regNo) regNo
    COALESCE(t1.points, 0) +  COALESCE(t2.points 0) points
FROM
    table1 t1
    FULL JOIN table2 t2 on t1.regNo = t2.regNo

答案 2 :(得分:0)

请检查此内容。您需要在聚合之前使用full outer join和null替换

select 
   COALESCE(table1.regno, table2.regno) regno,
   sum(COALESCE(table1.points,0)) + sum(COALESCE(table2.points,0)) points
from Table1 
full outer join Table2 
  on table1.regno = table2.regno
group by 
  COALESCE(table1.regno, table2.regno)