我在一个名为update,insert,delete的触发器中使用以下代码。 问题是当触发器运行时它会更新所有余额总计在发票表中相同.....它应该根据相应的invoicelines sum()更新每个发票总额,而不是将它们更新为全部相同。我已经坚持了几个小时,只是无法绕过它。
UPDATE invoices
SET invoices.Amount = (SELECT
SUM(invoicelines.Amount) AS expr1
FROM invoicelines i
INNER JOIN invoicelines
ON i.Id = i.Id
WHERE i.InvoiceId = i.InvoiceId
GROUP BY i.InvoiceId)
WHERE Id = Id;
答案 0 :(得分:2)
您应该使用外部WHERE子句:
WHERE id = NEW.id;
否则您将更新表中的每条记录,因为每条记录都会返回true,表明它们的ID等于它们的ID。
此外,如果您要删除或添加发票金额的发票金额,那就太多了。
你可以这样做:
对于INSERT
UPDATE invoices
SET Amount = Amount + NEW.amount
WHERE id = NEW.InvoiceId;
更新:
UPDATE invoices
SET Amount = Amount + NEW.amount - OLD.amount
WHERE id = NEW.InvoiceId;
对于DELETE:
UPDATE invoices
SET Amount = Amount - OLD.amount
WHERE id = OLD.InvoiceId;