MySql: 单个查询从不同表的两列计算

MySql: Single query to calculate from two columns of different tables

我有两张桌子

invoice_tbl

+---+---------+
|id | Amount  |
+---+---------+
|1  | 5000    |
|2  | 3200    |
|3  | 7400    |
+---+---------+

reciept_tbl

+---+-------------+-----------+
|id | invoice_id  |paid_amount|
+---+-------------+-----------+
|1  |      1      | 2000      |
|2  |      1      | 3000      |
|3  |      3      | 6400      |
+---+-------------+-----------+

在上述情况下,我想通过单个查询找出发票余额,以便我可以按余额做空。

感谢您的帮助。

做一个 GROUP BY,计算每个 ID 的余额 sum(i.Amount) - sum(r.paid_amount)

select i.id, sum(i.Amount) - sum(r.paid_amount) as balance
from invoice_tbl i
    left join reciept_tbl r on i.id = r.invoice_id
group by i.id

LEFT JOIN 包括没有任何付款的发票。