如何在mysql中基于distinct column连接两个表并求其列的和

zujrkrfu  于 2021-06-15  发布在  Mysql
关注(0)|答案(3)|浏览(307)

我用regno列连接两个表。我想在regno匹配的地方添加table1.points和table2.points的点,如果它不匹配,我也希望它和它的点一起包含在列表中,如下图所示

我已经通读了存在的问题,但没有找到解决办法,例如我如何在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`
);

我想让它给名单按照独特的(独特的)regno安排

iklwldmw

iklwldmw1#

请检查这个。你需要使用 full outer join 以及聚合前的空替换

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)
6mw9ycah

6mw9ycah2#

你在找一个 FULL JOIN 在两张table之间。

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
mrfwxfqh

mrfwxfqh3#

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

相关问题