1
mysql> select * from bills;
+----+------+-------+---------------------+---------------------+
| id | user | money | created_at          | updated_at          |
+----+------+-------+---------------------+---------------------+
|  1 | a    |   100 | 2023-05-20 23:15:53 | 2023-05-20 23:15:53 |
|  2 | b    |   200 | 2023-05-20 23:16:01 | 2023-05-20 23:16:01 |
+----+------+-------+---------------------+---------------------+
2 rows in set (0.00 sec)

mysql> select * from enroles;
+----+------+-------+---------------------+---------------------+
| id | user | money | created_at          | updated_at          |
+----+------+-------+---------------------+---------------------+
|  1 | b    |   300 | 2023-05-20 23:16:18 | 2023-05-20 23:16:18 |
|  2 | c    |   400 | 2023-05-20 23:16:24 | 2023-05-20 23:16:24 |
+----+------+-------+---------------------+---------------------+
2 rows in set (0.00 sec)


How to show user a,b,c and sum(money)?

I try group by and sum(), but failed...

Who can help me? thanks.

Patrick Su
  • 11
  • 3
  • Append your SQL attempt to the question, so that we know the attempt, and where you might not have the correct info. – Paul T. May 21 '23 at 00:54

1 Answers1

0

If you want to retrieve the total money from both tables per user, use UNION ALL to combine the result set of both SELECT statements, then apply GROUP BY and SUM() to get the intended output:

select `user`, sum(money) as total
from (
  select `user`, money
  from bills
  union all
  select `user`, money
  from enroles
) as s
group by `user`
SelVazi
  • 10,028
  • 2
  • 13
  • 29