MySQL JOINING 同一张表在 SUM() 上返回错误结果 [重复]
Posted
技术标签:
【中文标题】MySQL JOINING 同一张表在 SUM() 上返回错误结果 [重复]【英文标题】:MySQL JOINING same table returns wrong result on SUM() [duplicate] 【发布时间】:2021-12-21 03:58:50 【问题描述】:我有桌子 Clients
和 Orders
"Clients" | "Orders"
ID NAME | ID SENDER_CLIENT_ID RECEIVER_CLIENT_ID PRICE
1 Alex | 1 1 3 100
2 Scott | 2 2 3 300
3 Philipp | 3 1 2 200
| 4 1 2 400
| 5 3 1 300
预期输出:
ID NAME SENT_AMOUNT RECEIVED_AMOUNT
1 Alex 700 300
2 Scott 300 600
3 Philipp 300 400
我的查询输出:
ID NAME SENT_AMOUNT RECEIVED_AMOUNT
1 Alex 700 900
2 Scott 600 600
3 Philipp 600 400
MySQL 查询
SELECT c.id, name, sum(o.price) sent_amount, sum(o2.price) received_amount
FROM clients c LEFT JOIN orders o on c.id = o.sender_client_id LEFT JOIN orders o2 on c.id = t2.receiver_client_id
GROUP BY c.id
当我第二次加入“ORDERS”表时,我认为存在一个问题,因为它可能会带来重复的值,并从那里 SUMs() 重复。如何解决?
【问题讨论】:
【参考方案1】:尝试独立计算金额
select a.*, s.price send, t.price receive
from clients a
left join (
select sender_client_id, sum(price) price
from orders
group by sender_client_id
) s on a.id = s.sender_client_id
left join (
select receiver_client_id, sum(price) price
from orders
group by receiver_client_id
) t on a.id = t.receiver_client_id
【讨论】:
不知道我们可以使用 select next 块加入;谢谢。让我检查一下以上是关于MySQL JOINING 同一张表在 SUM() 上返回错误结果 [重复]的主要内容,如果未能解决你的问题,请参考以下文章