从3个表的条目求和

时间:2014-01-05 22:31:40

标签: mysql sql

我有5个具有相同布局的mysql表:

name|||||||||points
-------------------
name1|10
name2|9
name3|11

...

我想从用户的所有表中获取总和,因此结果应如下所示:

name|||||||||points
-------------------
name1|90
name2|59
name3|61
...

但我的问题是,有些表可能不包含name1,所以名称也可以在5个表中或1个中。

1 个答案:

答案 0 :(得分:1)

SELECT Q.Name, SUM(Q.POINTS_COLUMN) Total
FROM
 (
  SELECT Name , POINTS_COLUMN  FROM TABLE_ONE
  UNION ALL 
  SELECT Name , POINTS_COLUMN  FROM TABLE_TWO
  UNION ALL 
  SELECT Name , POINTS_COLUMN  FROM TABLE_THREE
  UNION ALL 
  SELECT Name , POINTS_COLUMN  FROM TABLE_FOUR
  UNION ALL 
  SELECT Name , POINTS_COLUMN  FROM TABLE_FIVE
  ) Q
GROUP BY Q.NAME