![](/img/trans.png)
[英]MySQL SELECT value from a table column based on a different table and sum()
[英]MySQL select a value from a table and sum values on another table based on the value from the first table
我有两个表,用户和销售。 我希望能够得到每个用户赚取的所有利润的总和。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.