尝试在invoices
表的UPDATE `invoices` SET invoices.`owes` = (`owes` - `paid`);
表中创建新触发器之后
我收到一个错误消息,因为我已经在payments
中更新了另一个触发器。 (见下文)
我希望将现有触发器保留在下面,但是如何进行修改以将owes
表中的owes
更新为(paid
-invoices
)。
CREATE TRIGGER `after_payment_update` AFTER UPDATE
ON `payments`
FOR EACH ROW UPDATE `invoices`
SET invoices.`paid` = (SELECT SUM(payments .`payment`)
FROM payments WHERE payments.`invoice` = invoices.`invoice`)
答案 0 :(得分:0)
您不能创建第二个触发器,该触发器“触发”与另一个触发器相同的动作。相反,您将使用如下所示的DELIMITER $$
语句,并在触发器中填充要执行的所有相关代码。
DELIMITER $$
CREATE TRIGGER after_update_payments
AFTER UPDATE ON payments
FOR EACH ROW BEGIN
UPDATE invoices
SET NEW.paid = (SELECT SUM(payment) FROM payments WHERE invoice = NEW.invoice),
NEW.owes = (owes -(SELECT SUM(payment) FROM payments WHERE invoice = NEW.invoice));
END $$
DELIMITER ;
您实际上在上面的触发器中不需要DELIMITER
,因此,我将向您展示一个示例,其中需要使用它:
DELIMITER $$
CREATE TRIGGER after_update_payments
AFTER UPDATE ON payments
FOR EACH ROW BEGIN
IF (some condition here) THEN
UPDATE invoices
SET NEW.paid = (SELECT SUM(payment) FROM payments WHERE invoice = NEW.invoice),
NEW.owes = (owes -(SELECT SUM(payment) FROM payments WHERE invoice = NEW.invoice));
END IF;
END $$
DELIMITER ;
作为一般规则,如果需要执行多个语句,这些语句的末尾需要使用;
,则需要使用DELIMITER
。如果这仍然没有道理,可以在here中找到有关分隔符的很好解释。
现在,顺便说一句,我认为这种方法不是最优的。在您遇到的情况下,我将要做的是创建一个合并这些表的视图。例如:
CREATE
ALGORITHM = UNDEFINED
DEFINER = `root`@`localhost`
SQL SECURITY DEFINER
VIEW invoice_payments_view AS (
SELECT
t1.*,
SUM(t2.payment) as amount_paid,
SUM(t2.owes - SUM(t2.payment)) as amount_owed
FROM invoices t1
JOIN payments t2 ON (t1.invoice=t2.invoice)
GROUP BY t1.invoice
)
然后要访问amount_paid
和amount_owed
列,您只需查询以下内容:
SELECT invoice, amount_paid, amount_owed FROM invoice_payments_view
WHERE invoice=1;
注意,我绝不是这个主题的专家,我只是向您展示如何应对这种情况。另外,我没有测试任何代码,因此您可能需要稍作修改。如果您有任何问题,请通知我,我可以进行更新。