我有两张桌子
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 |
+---+-------------+-----------+
在上述情况下,我想通过单一查询查找发票余额,以便我可以按余额金额进行缩短。
我赞美你的帮助。
答案 0 :(得分:0)
执行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
以包含发票而无需任何付款。