使用来自2个不同表的总和进行mysql计算

时间:2014-02-25 14:47:38

标签: mysql sql

如果有2个表:

TABLE "deposit"
card | amount
------------
2 | 123.43
2 | 56.45
3 | 21.19

+

TABLE "payment"
card | price | status
-----------
2 | 10.59 | finish
2 | 10.59 | pending
10 | 12.40 | finish
2 | 10.59 | finish

我要找的是卡片的剩余存款。

卡2的示例:123.43 + 56.45 - 10.59 - 10.59(仅状态=完成)

或:SUM(存款卡ID = 2) - SUM(卡ID = 2且状态=完成付款)

我尝试了以下mysql-select:

SELECT(
       IFNULL(SUM(deposit.amount),0) - IFNULL(SUM(payment.price),0)
        ) AS remaing_deposit
        FROM deposit, payment
        WHERE deposit.card = '2'
        OR (
            payment.card = '2' AND payment.status = 'finish'
        )

但我得到完全错误的数字。

有人能帮助我吗?

1 个答案:

答案 0 :(得分:2)

这里面临的一个挑战是两张牌中有不同的牌。 MySQL不支持full outer join。您可以获取执行union的卡片列表。

通过使用from left outer join上的allcards聚合select allcards.card, coalesce(d.deposit, 0) - coalesce(p.price, 0) as RemainingDeposit from (select card from deposit union select card from payment ) allcards left outer join (select card, sum(amount) as deposit from deposit group by card ) d on d.card = allcards.card left outer join (select card, sum(price) as price from payment where status = 'finish' group by card ) p on p.card = allcards.card; 子句中的两个表来解决查询的其余部分:

{{1}}