2013-07-07 58 views
0

我有几个相同的表。他们是这样的:如何从两个或多个相同的mysql表中汇总结果?

Table 1 
-------------------- 
Username  Points 
User 1   10 
User 2   15 
User 2   1 
User 1   3 

Table 2 
--------------------- 
Username  Points 
User 1    10 
User 2    15 
User 2    5 
User 1    15 

我使用SELECT username, SUM(points) AS total_points来计算特定用户的点。它的工作非常完美。但我想从两个或多个表中总结结果。那可能吗?

+0

欢迎来到Stack Overflow。如果您的问题的答案证明有用,请点击绿色复选框接受它。 –

回答

0

如果您不想丢弃表格之间的重复项,请使用UNION ALL

select username, sum(points) as total_points 
from (
    select username, points 
    from table_1 
    union all 
    select username, points 
    from table_2 
) t 

如果使用UNION代替,然后使用相同的用户名和分行将只能算作(总结)一旦

但它听起来像你真正应该将它放入一个表。您可能需要阅读数据库规范化。

+0

非常感谢!工作完美! :))) – user2394960