挣扎于MySQL触发器

问题描述 投票:0回答:1

我想创建一个触发器,将订单中所有产品的总和插入付款,但我面临语法错误。这是我到目前为止所写的内容:

CREATE TRIGGER set_total BEFORE INSERT on payments 
FOR EACH ROW 
BEGIN

DECLARE id INT(10);

DECLARE temp INT(10);

SET id:=new.Order;

SELECT SUM(Price) into temp

FROM products , order_products

WHERE order_products.Order LIKE id AND products.Products_ID=order_products.Products;

SET new.Total:=temp;

END;

我无法弄清楚我的语法错误,请帮忙。

编辑:#1064 - 您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在第2行的''附近使用正确的语法

mysql triggers phpmyadmin
1个回答
1
投票

在多语句触发器,过程等...你需要暂时覆盖分隔符,所以MySQL不认为它运行的第一个;结束触发器/过程/等...

DELIMITER $$

CREATE TRIGGER set_total BEFORE INSERT on payments 
FOR EACH ROW 
BEGIN

DECLARE id INT(10);
DECLARE temp INT(10);

SET id:=new.Order;

SELECT SUM(Price) into temp
FROM products , order_products
WHERE order_products.Order LIKE id AND products.Products_ID=order_products.Products;

SET new.Total:=temp;

END$$

DELIMITER ;

旁注:这通常被认为是用于计算总和的更好的查询形式:

SELECT SUM(Price) into temp
FROM products
INNER JOIN order_products ON products.Products_ID=order_products.Products
WHERE order_products.Order = id;

另外:小心声明可能被模糊地解释为字段名称的变量名称;如果products和/或order_products有一个id字段,那么“where”条件可能会导致意外结果;充其量它仍然会使它不必要地难以阅读。

© www.soinside.com 2019 - 2024. All rights reserved.