首页 > 解决方案 > 插入新记录后如何创建更新触发器?

问题描述

我在mysql.Table 名称中创建了表,sales其中包含以下列 saleID int NOT NULL Primary Key, productID int NOT NULL, unitPrice decimal(6,2) NOT NULL, quantity int NOT NULL, total decimal(6,2) 现在我想要update trigger在插入新记录后找到此次销售的总价。

我正在尝试编写更新触发器

DELIMITER $$
CREATE TRIGGER before_sales_insert  
before INSERT ON sales
FOR EACH ROW 
 BEGIN

END#
$$
DELIMITER 

我是初学者,请帮助。谢谢

标签: mysqltriggersdatabase-trigger

解决方案


给定

select productid ,standardcost from awproduct where productid = 707;
+-----------+--------------+
| productid | standardcost |
+-----------+--------------+
|       707 |         3.00 |
+-----------+--------------+

并假设您在调用触发器之前尚未获得单价

drop table if exists t;
drop trigger if exists t;
create table t
(id int, productid int, unitprice int, quantity int, totalprice int);

delimiter $$
create trigger  t
before insert on  t
for each row begin
    set new.unitprice = (select standardcost from awproduct where productid = new.productid);
    set new.totalprice = new.quantity * new.unitprice;

end $$
delimiter ;

insert into t (id,productid,quantity) values
(1,707,10);

select * from t;

+------+-----------+-----------+----------+------------+
| id   | productid | unitprice | quantity | totalprice |
+------+-----------+-----------+----------+------------+
|    1 |       707 |         3 |       10 |         30 |
+------+-----------+-----------+----------+------------+
1 row in set (0.00 sec)

我无法改进手册中的文档,所以我不会尝试。顺便说一句,如果您想要一个更接近您要求的解决方案,最好将示例数据作为文本包含在问题中。


推荐阅读