【问题标题】:MySQL select a value from a table and sum values on another table based on the value from the first tableMySQL 从一个表中选择一个值,并根据第一个表中的值对另一个表中的值求和
【发布时间】:2021-03-29 08:00:14
【问题描述】:

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

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

【问题讨论】:

    标签: mysql sql join sum subquery


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      试试

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-26
        • 1970-01-01
        相关资源
        最近更新 更多