如何根据不同的列连接两个表并在 Mysql 中对它们的列求和

How to Join two tables and sum their columns across in Mysql based on distinct column

我正在通过 regNo 列连接两个表。我想在 regNo 匹配的地方添加 Table1.points 和 Table2.points 的点,以防万一它不匹配我也希望它与它的点一起包含在列表中,如下图所示

我已经通读了现有的问题,但没有找到解决方案,例如 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 排列的列表

您正在寻找两个表之间的 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

注意:您没有指定生成新 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

请检查这个。您需要在聚合之前使用 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)

您需要 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