0

我需要一个函数或触发器来解决这个问题??

顾客信息 :::

custid    name    creditid
----------------------------
   2        a        1 
   3        b        2
   4        c        3

余额 :::

creditid   credit_type    balance
-----------------------------------
    1         rent        1000
    1         transport   2000
    1         food        1000
    1         fruits      1500
    2         rent        1500
    2         transport   1020
    2         food        1200
    2         fruits      1000
    3         transport   1600
    3         rent        2000
    3         food        1540
    3         fruits      1560

Pay_the_loan :::

creditid   credit_type       Pay      status
---------------------------------------------
    1         rent           500       null
    2         fruits         600       null
    3         transport      400       null
    1         fruits         500       null

一旦我将status列更新pay_the_loan tableok特定的creditid即,

(更新 pay_the_loan set status='ok' where creditid=2)

then它应该是 balance_amount 表deduct中列中的金额,balance并且应该更新,即(1000-600=400在 balance_amount 表中wherebalance_amount.credit_type=fruits 和 creditid=2 来自余额表)

可以给我发一个Function或一个Trigger来解决这个问题吗?

4

2 回答 2

0

您可能最好稍微重组一下,loan_amount用原始贷款创建一个表,然后创建balance_amount一个视图来显示当前余额并扣除所有付款。这样,例如,付款金额的更正不会使您的系统显示错误的余额。

为您计算当前余额的视图可能类似于:

CREATE VIEW balance_amount AS
    SELECT la.creditid, la.credit_type, amount 
              - COALESCE(SUM(pay),0) balance
    FROM loan_amount la
    LEFT JOIN pay_the_loan pl
      ON la.creditid = pl.creditid 
     AND la.credit_type = pl.credit_type
     AND pl.status = 'OK'
    GROUP BY la.creditid, la.credit_type, la.amount;

一个带有整个设置的 SQLfiddle

于 2013-07-10T12:40:05.207 回答
0

您可以在同一查询中更新两个表:

update
    pay_the_loan
set
    pay_the_loan.status='ok',
    balance_amount.balance=balance_amount.balance-pay_the_loan.Pay
from balance_amount
where
    pay_the_loan.creditid=balance_amount.creditid
    and
    pay_the_loan.creditid=2
    and
    balance_amount.credit_type='fruits';

更新。我已经阅读了postgresql语句的文档。update显然,我错了,不可能在一个查询中更新两个表。但是,我仍然认为您在这里不需要触发器。只需一个接一个地使用两个更新查询:

update
    pay_the_loan
set
    status='ok'
where
    pay_the_loan.creditid=2;

update
    balance_amount
set
    amount=balance_amount.amount-pay_the_loan.Pay
from pay_the_loan
where
    pay_the_loan.creditid=balance_amount.creditid
    and
    pay_the_loan.creditid=2
    and
    balance_amount.credit_type='fruits';
于 2013-07-10T12:45:56.967 回答