简体   繁体   English

如何从两个或多个相同的mysql表求和?

[英]How to SUM results from two or more identical mysql tables?

I've got a couple of identical tables. 我有几个相同的桌子。 They look like this: 他们看起来像这样:

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 

I'm using SELECT username, SUM( points ) AS total_points to calculate the points for particular user. 我正在使用SELECT username, SUM( points ) AS total_points计算特定用户的积分。 And it workds perfect. 它工作完美。 But i want to SUM the results from two or more tables. 但是我想对两个或多个表的结果求和。 Is that possible? 那可能吗?

Use a UNION ALL if you don't want to discard duplicates between the tables. 如果您不想丢弃表之间的重复项,请使用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

If you use UNION instead, then rows with the same username and points will only be counted (summed) once 如果改用UNION ,则具有相同用户名和分数的行将仅被计数(累加)一次

But it sounds like you actually should put that into a single table. 但是听起来您实际上应该将其放在单个表中。 You might want to read up on database normalization. 您可能想了解数据库规范化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM