如何 Select 出现在两个表中的实体的总和

How To Select the total sum of an entity that appears in two tables

我有两种类型的吸引力表,其中一个用户可以出现在一个或两个表中我的目标是获得每个用户的总和。表格如下。

 users
------------+----------+
| user_id   | Name     |
+-----------+----------+
| 1         | John     |
------------+----------+
| 2         |  Wells   |
------------+----------+

 shop1
------------+----------+--------------+
| trans_id  | user_id  | amount_spent |
+-----------+----------+--------------+
| 1         |   1      |   20.00      |
------------+----------+--------------+
| 2         |   1      |   10.00      |
------------+----------+--------------+

 shop2
------------+----------+--------------+
| trans_id  | user_id  | amount_spent |
+-----------+----------+--------------+
| 1         |   2      |   20.05      |
------------+----------+--------------+

求和后的预期结果

------------+-------------+
| user      | Total Spent |
+-----------+-------------+
| John      |   30.00     |
------------+-------------+
| Wells     |   20.05     | 
------------+-------------+

您可以使用 union all 和聚合:

select user_id, sum(amount_spent) total_spent
from (
    select user_id, amount_spent from shop1
    union all
    select user_id, amount_spent from shop2
) t
group by user_id

使用union allgroup by:

select user_id, sum(amount_spent)
from ((select user_id, amount_spent from shop1) union all
      (select user_id, amount_spent from shop2)
     ) s
group by user_id;

也就是说,您的数据模型很差。一般来说,table 具有相同的列是一个非常糟糕的主意。您应该为所有商店设置一个 table,并为商店设置一个附加列。

如果你想要名字,你需要join:

select u.name, sum(amount_spent)
from users u join
     ((select user_id, amount_spent from shop1) union all
      (select user_id, amount_spent from shop2)
     ) s
     using (user_id)
group by user_id, u.name;
select user_id, sum(amount_spent)
from
(shop1
UNION ALL
ship2)
group by user_id