Postgresql

根據子表的值創建觸發器以更新父表的狀態

  • October 27, 2021
Table order 
columns - id  status
          1  confirmed 

Table trays
columns - id,orderid(fk),status
          1   1        done
          2   1        processing

只有在完成與特定訂單相關的所有托盤元素後,我才必須將訂單表的狀態更新為完成,例如。一個訂單有兩個托盤一旦兩個托盤的狀態都更改為完成,那麼我需要將訂單的狀態更新為完成。無論如何用更新後觸發器來處理這種情況?提前致謝

看來您需要:

CREATE TRIGGER fix_order_status
AFTER UPDATE
ON trays
FOR EACH ROW
UPDATE order
SET order.status = 'confirmed'
WHERE order.id = NEW.orderid
 AND NOT EXISTS ( SELECT NULL
                  FROM trays
                  WHERE trays.orderid = NEW.orderid
                    AND trays.status <> 'done' );

展示

引用自:https://dba.stackexchange.com/questions/301701