簡體   English   中英

我想在另一張表中插入一行后更新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 pointsamount

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上的列pointsamount

嘗試這種方式:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM