Search code examples
mysqlsqljoinsumsubquery

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


I have two tables, users and sales. I want to be able to get the sum of all profits made by each user.

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

Solution

  • One option uses a correlated subquery:

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