我有几个相同的 table 。它们看起来像这样:
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) AStotal_points
来计算特定用户的积分。而且效果很完美。但我想对两个或多个表的结果求和。那可能吗?
最佳答案
如果您不想丢弃表之间的重复项,请使用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
,则具有相同用户名和积分的行将仅计算(求和)一次
但听起来您实际上应该将其放入一个表中。您可能想阅读有关数据库规范化的内容。
关于php - 如何对两个或多个相同的 mysql 表的结果求和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17512921/