问题描述
我有 3 个 MysqL 表,我想制作通过将两个不同表中的两个字段相乘而生成的字段之一。这些是我的表:
物品
id_item | price
1 | 20
2 | 30
3 | 50
详细交易
id_trans(fk) | id_item | total_items
1 | 1 | 1
1 | 2 | 1
1 | 3 | 1
交易
id_trans | total_price
1 | 100
TRANSACTIONS 中的 total price
字段是我想要的,我尝试制作一个触发器,例如:
CREATE TRIGGER total_price
AFTER INSERT ON detail_transactions
FOR EACH ROW
UPDATE transactions
SET transactions.`total_price`=
(SELECT SUM(items.'price'*detail_transactions.'total_items')
FROM items
JOIN detail_transactions
ON items.'id_item'= detail_transactions.`id_item`)
WHERE transactions.`id_trans` = NEW.`id_trans`;
但结果不是我想要的。任何帮助将不胜感激!
解决方法
关键字是 FOR EACH ROW - 即一次更新 1 行..并且不要假设事务存在测试并在需要时创建
drop trigger if exists t;
delimiter $$
create trigger t after insert on detail_transactions
for each row begin
if not exists (select 1 from transactions t where t.id_trans = new.id_trans) then
insert into transactions
select new.id_trans,new.total_items * price
from items
where items.id_item = new.id_item ;
else
update transactions join items on items.id_item = new.id_item
set total_price = total_price + (new.total_items * price);
end if;
end $$
,
CREATE TRIGGER tr_ai_update_total_price
AFTER INSERT
ON detail_transactions
FOR EACH ROW
REPLACE INTO transactions (id_trans,total_price)
SELECT NEW.id_trans,SUM(items.price * detail_transactions.total_items)
FROM items
JOIN detail_transactions USING (id_item)
WHERE transactions.id_trans = NEW.id_trans;
此查询假定 transactions (id_trans)
被定义为 UNIQUE
(可能是 PRIMARY KEY
)。
如果此 id_trans
的行已经存在,它将被新值替换。如果它不存在,则将其插入。
触发器创建语句包含 1 个语句,因此不需要 BEGIN-END 和 DELIMITER。