[英]create trigger to update a table on inserting new row in another table in MySQL
[英]I want to update a table in mysql after inserting a row into another table
我有兩張桌子
bill
(id,amount,points)
bill_history
(id,bill_id,amount,points)
當將一行插入bill_history時,我想總結bill_history表中的金額和積分,因此應根據bill_id在bill表中對其進行更新
您只需在bill_history
表上創建一個AFTER INSERT
觸發器bill_history
。
在此觸發器中,您可以編寫邏輯以更新bill
表中的SUM(AMOUNT)
和SUM(POINT)
。
您可以使用TRIGGER
:
DELIMITER |
CREATE TRIGGER ins_bill_history AFTER INSERT ON bill_history
FOR EACH ROW
BEGIN
UPDATE bill
SET points = (SELECT SUM(points) FROM bill_history WHERE bill_history.bill_id = NEW.bill_id),
amount = (SELECT SUM(amount) FROM bill_history WHERE bill_history.bill_id = NEW.bill_id)
WHERE bill.id = NEW.bill_id;
END;
|
另一個解決方案是使用VIEW
來即時SUM
points
和amount
:
CREATE VIEW v_bill AS
SELECT bill.*, SUM(bh.points) AS 'points', SUM(bh.amount) AS 'amount'
FROM bill b INNER JOIN bill_history bh ON b.id = bh.bill_id
GROUP BY b.id
注意:如果使用VIEW
,則必須刪除表bill
上的列points
和amount
。
嘗試這種方式:
INSERT INTO YourTable(columns....)
VALUES(..........)
SET v_lastinsertedrecord = LAST_INSERT_ID()
UPDATE YourTable SET (COLUMNS='value') WHERE id=@lastinsertedrecord
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.