2017-08-31 64 views
0

後更新MySQL中的表我有兩個表我想插入一行到另一個表

bill 
(id,amount,points) 

bill_history 
(id,bill_id,amount,points) 

當行插入bill_history,我想總結一下從bill_history表的數量和點它應該根據bill_id更新在帳單表中

+0

請幫助我。它可以通過觸發兩個查詢來完成,但我想知道如何通過觸發器來完成,或者可能是函數。 –

回答

0

您可以簡單地在bill_history表上創建一個觸發AFTER INSERT

而在此觸發器中,您可以編寫邏輯以更新bill表中的SUM(AMOUNT)SUM(POINT)

0

您可以使用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; 
| 

另一種解決方案是使用一個VIEWSUM對飛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您必須刪除表中的列points和。

+0

1064 - 您的SQL語法錯誤;檢查與你的MySQL服務器版本相對應的手冊,在'|'附近使用正確的語法在第6行 –

+0

爲什麼觸發givng語法錯誤 –

+0

您的查詢必須以'DELIMITER |'開頭!更好的解決方案是使用「VIEW」解決方案。 –

0

試試這樣說:

INSERT INTO YourTable(columns....) 
    VALUES(..........) 

SET v_lastinsertedrecord = LAST_INSERT_ID() 

UPDATE YourTable SET (COLUMNS='value') WHERE [email protected] 
相關問題