多个mysql表列的Sum,Subtract和Join
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多个mysql表列的Sum,Subtract和Join相关的知识,希望对你有一定的参考价值。
我有四个mysql表client
,transaction
,other_loan
和payment
。我想得到sum
和load_amount
的additional
从transaction
和sum
的amount
表other_loan
+ subtract
到表sum
的payment_amount
的payment
。我怎样才能实现它?
结果我想:
> ID | Name | Amount
> 1 | Robin | 8718
> 2 | Reynaldo | 21
> 3 | Leomar | 0
我的表:交易
> tid | id| date | load_amount | additional
> 1 | 1 | 2018-12-01 | 90 | 0
> 2 | 1 | 2018-12-07 | 90 | 0
> 3 | 2 | 2018-12-08 | 49 | 2
表:other_loan
> oid | id| amount | date
> 1 | 1 | 7928 | 2018-12-10
> 2 | 1 | 750 | 2018-12-10
表:付款
> pid |id | payment_amount | date
> 1 | 1 | 50 | 2015-12-10
> 2 | 1 | 90 | 2015-12-10
> 3 | 2 | 30 | 2015-12-10
表:客户
> id | Name |
> 1 | Robin |
> 2 | Cinderella |
> 3 | Leomar |
答案
由于您有多个交易,其他贷款金额和每个客户的付款,您不能互相执行表格的直接JOIN
,因为它会导致行的复制,从而导致错误的值。相反,在执行SUM
之前,我们在客户端基础上JOIN
每个表中的所有值。此外,由于某些客户端在每个表中都没有条目,因此必须在结果上使用LEFT JOIN
s和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
以上是关于多个mysql表列的Sum,Subtract和Join的主要内容,如果未能解决你的问题,请参考以下文章