2016-02-04 43 views
0

我有PostgreSQL的事務,我執行以下命令:PostgreSQL鎖定行之前刪除?

  1. SELECT "amount", "accountId" from "transactions" where "id" = "123"
  2. DELETE from "transactions" where "id" = "123"
  3. UPDATE "accounts" set "balance" = "balance" - amountFetchedInCommand1 where "id" = accountFetchedInCommand1

現在我需要確保命令1和2行之間取自transactions不會被修改(特別是其amountaccountId字段)。

我可以使用SELECT FOR UPDATE語句來鎖定在命令1處獲取的行,即使我不打算更新該行但只是將其刪除嗎?

否則確保此操作始終正確運行的最佳方法是什麼?

transactions.accountId是掛account.idON DELETE CASCADE外鍵)

+1

是的,你可以使用'選擇update'但爲什麼你需要的'select'呢?爲什麼不直接刪除行?一旦它被刪除,無論如何沒有其他交易可以修改它。順便說一句:''123「'是一個列名不是數字。您應該使用'where id = 123' –

+0

@a_horse_with_no_name謝謝,我需要從中獲取「金額」值,以便我可以更新鏈接的「帳戶」行中的餘額 –

+0

並且postgresql不會返回已刪除的行 –

回答

2

您可以在一個單一的語句來完成步驟2和步驟3:

with deleted as (
    DELETE from transactions 
    where id = 123 
    return amount, "accountId" 
) 
UPDATE accounts 
    set balance = accounts.balance - d.amount 
from deleted d 
where accounts.id = d."accountId";