我有四个mysql表client
,transaction
,other_loan
和payment
。我想从sum
和{{中获取表load_amount
的{{1}}和additional
到表transaction
的{{1}}和sum
的{{1}} 1}}到表amount
中other_loan
的{{1}}中。我该如何实现?
我想要的结果:
subtract
我的桌子: 交易
sum
表:other_loan
payment_amount
表格:付款
payment
表:客户
> ID | Name | Amount
> 1 | Robin | 8718
> 2 | Reynaldo | 21
> 3 | Leomar | 0
答案 0 :(得分:1)
由于您有多个交易,其他每个客户的贷款额和还款额,因此您无法对表进行直接JOIN
的交互操作,因为这将导致行的复制,从而导致错误的值。取而代之的是,我们在做SUM
之前,先在客户基础上JOIN
在客户端基础上每个表中的所有值。另外,由于某些客户端在每个表中都没有条目,因此您必须在结果上使用LEFT JOIN
和COALESCE
,以便空行不会导致SUM变为NULL
。此查询应为您提供所需的结果:
SELECT c.id, c.name,
COALESCE(t.transactions, 0) + COALESCE(o.amounts, 0) - COALESCE(p.payments, 0) AS amount
FROM client c
LEFT JOIN (SELECT id, SUM(load_amount) + SUM(additional) AS transactions
FROM transaction
GROUP BY id) t on t.id = c.id
LEFT JOIN (SELECT id, SUM(amount) AS amounts
FROM other_loan
GROUP BY id) o ON o.id = c.id
LEFT JOIN (SELECT id, SUM(payment_amount) AS payments
FROM payment
GROUP BY id) p ON p.id = c.id
GROUP BY c.id
输出(用于您的示例数据):
id name amount
1 Robin 8718
2 Cinderella 21
3 Leomar 0