2013-07-10 89 views
0

我需要一個函數或觸發器來解決這個問題?如何更改另一個表中的同一列時更改列(postgresql)

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 

一旦我在pay_the_loan tablestatus柱更新爲ok用於特定creditid i .E ..,

(更新pay_the_loan設置狀態= 'OK',其中creditid = 2)

then應該deduct在BALANCE_AMOUNT表從balance柱的量和它應該被更新,即,(1000-600 = 400在BALANCE_AMOUNT表where balance_amount.credit_type =水果和creditid = 2從平衡量表)

可能交我FunctionTrigger來解決這個親呃?

+0

'1)'定義條件:更新何時應該發生? '2)'定義實際的更新語句:應該改變什麼,以及如何? '3)'將'2'變換成一個函數,'1'變成一個觸發器。 '4)'利潤! '0)'你需要一些表格中的PG/FK。 – wildplasser

+0

好吧,我會帶着一個這樣的例子,讓這個更好的理解!問題@ wildplasser – 09Q71AO534

回答

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; 

An SQLfiddle with the whole setup

+0

http://sqlfiddle.com/#!12/7846f/1相同的邏輯在這裏不工作可以清除這個... @ joachim Isaksson – 09Q71AO534

+0

@ user2561626對不起,'IFNULL'應該是'COALESCE' for PostgreSQL的。 http://sqlfiddle.com/#!12/7846f/4 –

+0

它可以解釋你更多! http://sqlfiddle.com/#!12/61942/1 – 09Q71AO534

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'; 
+0

這是SQL FIDDLE sqlfiddle.com/#!12/3e6a7/18請解決這個查詢... @mikhail makarov – 09Q71AO534

+0

你試過我的方法嗎?你不需要功能也不需要觸發器。您可以在將狀態設置爲'ok'的相同查詢中更新餘額。你明白我的建議嗎? –

+0

http://sqlfiddle.com/#!12/35a5e/2它給出了幾個錯誤 – 09Q71AO534

相關問題