0

我想创建一个触发器,它会在同一个表中自动更新我的“比率”列。我需要按日期(月和年)对特定项目进行排序,得到该日期项目的总和,然后除以项目值。

这是我尝试过的查询:

create trigger ratio
before update
ON Table1
for each row
(select Month,Year,sum(item_value) as sum_item
    from Table1
    where item_name like ('BUC%')
    group by Month,Year) x
on Table1.Month = x.Month and Table1.Year = x.Year and Table1.item_name like ('BUC%')
set Table1.Ratio = Table1.item_value/x.sum_item;

但我得到了Error Code: 1415. Not allowed to return a result set from a trigger我理解的错误。顺便说一句,我对 mysql 很陌生。

如果我不能以这种方式做我想做的事,是否有另一种方法或方法来完成它?

4

1 回答 1

0

使用子查询获取相同产品和月份的总值,并使用它来计算更新行的比率。

DELIMITER $$

create trigger ratio
before update
ON Table1
for each row
IF item_name LIKE 'BUC%'
THEN
    SET NEW.ratio = NEW.item_value/(
        SELECT SUM(item_value) 
        FROM Table1 
        WHERE item_name = NEW.item_name AND month = NEW.month AND year = NEW.year
    );
END IF$$

DELIMITER ;
于 2021-09-30T21:09:55.543 回答