我有两张桌子
bill
(id,amount,points)
bill_history
(id,bill_id,amount,points)
当在bill_history中插入一行时,我想总结一下bill_history表中的金额和点数,并且应该根据bill_id在账单表中更新
答案 0 :(得分:0)
您只需在Definer
表格上创建一个触发器AFTER INSERT
。
在此触发器中,您可以编写逻辑来更新bill_history
表中的SUM(AMOUNT)
和SUM(POINT)
。
答案 1 :(得分: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;
|
另一种解决方案是动态使用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
,则必须删除表points
上的列amount
和bill
。
答案 2 :(得分:0)
尝试这种方式:
INSERT INTO YourTable(columns....)
VALUES(..........)
SET v_lastinsertedrecord = LAST_INSERT_ID()
UPDATE YourTable SET (COLUMNS='value') WHERE id=@lastinsertedrecord