将两个不同 table 中的两列相乘并使用触发器将它们设置为另一个 table

Multiply two column from two different table and set them into another table using triggers

我有 3 个 Mysql 表,我想通过将两个不同表中的两个字段相乘生成其中一个字段。这些是我的表格:

ITEMS

id_item |  price
1       |   20
2       |   30
3       |   50

DETAIL TRANSACTIONS

id_trans(fk) | id_item | total_items
1            |    1    |     1
1            |    2    |     1
1            |    3    |     1

TRANSACTIONS

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`;

但是结果不是我想要的。任何帮助将不胜感激!

关键字针对每一行 - 即一次更新 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。