mysql - 插入新记录后如何创建更新触发器?
问题描述
我在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
我是初学者,请帮助。谢谢
解决方案
给定
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)
我无法改进手册中的文档,所以我不会尝试。顺便说一句,如果您想要一个更接近您要求的解决方案,最好将示例数据作为文本包含在问题中。
推荐阅读
- c# - 无状态服务与想要成为单例的 HttpClient
- .htaccess - .htaccess 将 https://www 重定向到非 www 用于通配符子域
- swift - MFMailComposeViewControllerDelegate 没有在其他类 swift 4 中被调用
- javascript - javascript - 从光标后的一点开始画一条线
- reactjs - React 服务器渲染应用程序中 ComponentDidMount 的替代方案是什么?
- vba - VBA CountIF 不会计算整个列
- sql - 如何从喜欢的地方选择特殊字符 - SQL Server
- tsql - 当日期以朱利安格式存储为 int 时,获取最近 5 天的数据
- javascript - javascript将数字四舍五入到小数点后两位
- go - 使用 golang dep 来自同一 github 源的不同包版本