MySQL select 来自 table 的值,并根据第一个 table 的值对另一个 table 的值求和

MySQL select a value from a table and sum values on another table based on the value from the first table

我有两个表,users 和 sales。我希望能够得到每个用户所赚取的所有利润的总和。

Users
_ _ _ _  _ _ _ _ _ _ 
|id                  |
|first_name          |
|second_name         |
|                    |
|                    |
|                    |
|                    |
 _ _ _ _ _ _ _ _ _ _ 
Sales
_ _ _ _  _ _ _ _ _ _ 
|id                  |
|user                |
|profit              |
|                    |
|                    |
|                    |
|                    |
 _ _ _ _ _ _ _ _ _ _ 

一个选项使用相关子查询:

select u.*,
    (select sum(s.profit) from sales s where s.user = u.id) as total_sales
from users u

尝试

SELECT
    u.second_name,
    u.first_name,
    SUM(s.profit)
FROM
    sales AS s
  JOIN
    users AS u ON u.id = s.user
GROUP BY
    u.id