两个表中两列的总和

时间:2016-05-22 17:33:34

标签: mysql sum

我有两个表,需要获得两列的总和(每个表中有一列)。

  • 桌面游戏(id_tournament,id_game,电子邮件,积分)PK(id_tournament,id_game,email)
  • 表格结果(id_tournament,电子邮件,积分)PK(id_tournament,email)
  • 表用户(id_user,email,name)PK(id_user)

示例表结果:

1,me@hotmail.com,3 
1,you@hotmail.com,4

示例表游戏:

1,1,me@hotmail.com,5  
1,2,me@hotmail.com,3  
1,3,me@hotmail.com,2   
1,1,you@hotmail.com,4  
1,3,you@hotmail.com,2

示例表用户:

1,me@hotmail.com,John  
2,you@hotmail.com,Peter

我的输出应该是:

John 13  
Peter 10

我尝试使用

SELECT t3.name, SUM(t1.points+t2.points) as Total 
FROM user t3, games t1, results t2 
WHERE  t1.email=t2.email AND t2.email=t3.email AND  t1.id_tournament=t2.tournament 
GROUP BY t1.email 
ORDER BY Total DESC

但得到了非常奇怪的数字。

1 个答案:

答案 0 :(得分:2)

从游戏表中获取总积分,从结果表中获得总积分,然后将它们合计。

这样的事情:

 SELECT v.name
      , SUM(v.points) AS points
   FROM (
          SELECT gu.name
               , SUM(g.points) AS points
            FROM games g
            JOIN user gu
              ON gu.email = g.email
           GROUP BY gu.name

           UNION ALL

          SELECT ru.name
               , SUM(r.points) AS points
            FROM results r
            JOIN user ru
              ON ru.email = r.email
           GROUP BY ru.name   
        ) v
    GROUP BY v.name
    ORDER BY v.name

修改

添加了缺少的GROUP BY子句。

如果我们需要从用户表中返回所有名称的值,即使游戏或结果中没有相关的行...

 SELECT n.name
      , IFNULL(SUM(v.points),0) AS points
   FROM users n
   LEFT
   JOIN (
          SELECT gu.name
               , SUM(g.points) AS points
            FROM games g
            JOIN user gu
              ON gu.email = g.email
           GROUP BY gu.name

           UNION ALL

          SELECT ru.name
               , SUM(r.points) AS points
            FROM results r
            JOIN user ru
              ON ru.email = r.email
           GROUP BY ru.name   
        ) v
      ON v.name = n.name
    GROUP BY n.name
    ORDER BY n.name