我需要一个函数或一个触发器来解决这个问题吗?
customer_details :::
custid name creditid
----------------------------
2 a 1
3 b 2
4 c 3
balance_amount :::
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 table
列更新为ok
特定creditid
,即
(更新pay_the_loan设置状态='ok',其中creditid = 2)
then
它应该deduct
来自balance_amount表中balance
列的金额,并且应该更新,即。,(1000-600 = 400
在balance_amount表{ {1}} balance_amount.credit_type = fruits和creditid = 2来自余额金额表)
可以发贴where
或Function
来解决此问题吗?
答案 0 :(得分: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;
答案 1 :(得分: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
语句的the documentation。显然,我错了,并且无法在单个查询中更新两个表。但是,我仍然认为你不需要触发器。只需一个接一个地使用两个更新查询:
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';