如何从具有不同结构的多个表中求和?

How to sum from multiple tables with different structure?

您好,我正在尝试通过使用 SQL 查询总结 'likes' 和 'amount' 的奖励并减去 [= =42=]

我可以从一个 table 中得到总和,但无法让它与多个 table 一起正常工作,

两个table的table结构不同,我找不到任何与我相同的问题..

这是我的第一篇table“文章”

username likes dislikes
Bob 3 -1

这是我的第二个table“奖项”

username amount
Bob 3

在这种情况下它应该输出 5 但我无法让它工作

 SELECT SUM(rep) AS totalRep FROM 
  (
    SELECT `likes` FROM `articles` UNION ALL
    SELECT `dislikes` FROM `articles` UNION ALL
    SELECT `amount` FROM `awards` UNION ALL
  ) GROUP BY `username`

我也试过这样..

SELECT SUM(rep) AS totalRep FROM 
  (
    SELECT SUM(likes) FROM `articles` UNION ALL
    SELECT SUM(dislikes) FROM `articles` UNION ALL
    SELECT SUM(amount) FROM `awards` UNION ALL
  ) GROUP BY `username`

像这样..

SELECT rep SUM(totrep) AS totrep FROM 
(
  SELECT likes,dislikes FROM `articles`
  UNION ALL
  SELECT amount FROM `awards`
) GROUP BY `username`

和..

SELECT SUM(likes,dislikes,amount) AS totrep
  FROM (
        SELECT likes,dislikes FROM `articles`
        UNION ALL
        SELECT amount FROM `awards`
       )  GROUP BY `username`

对于 articles table 你需要加总喜欢+不喜欢,然后使用 union all。

尝试:

select username,sum(amount) as totalRep
FROM ( 
       select username,
              (sum(likes)+sum(dislikes)) as amount
       from articles
       group by username
    union all
       select username,
              amount
     from awards
     ) as t1
group by  username;     

https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=bee2cf836d5a7b76cea65e3b773e880c