如何在删除触发器后更新 table 中的行

How to update rows in table in after delete trigger

我有一个tablecountry_group

+------+----------+--------+
| code | group_id | weight |
+------+----------+--------+
| me   | 1        | 50.00  |
+------+----------+--------+
| me   | 2        | 10.00  |
+------+----------+--------+
| me   | 3        | 40.00  |
+------+----------+--------+

对我来说,每个国家/地区的列权重总和为 100 非常重要。我想在这里做的是,当我删除其中一行时,我需要更改该国家/地区的权重值,以便所有的总和该国家/地区的权重仍然是 100。我想为此在我的数据库中设置触发器。

例如,如果我删除权重为 10.00 的行,那么 table 应该如下所示:

+------+----------+--------+
| code | group_id | weight |
+------+----------+--------+
| me   | 1        | 55.00  |
+------+----------+--------+
| me   | 3        | 45.00  |
+------+----------+--------+

所以这是我的触发器:

CREATE DEFINER = CURRENT_USER TRIGGER   extensionui2.country_group_AFTER_DELETE 
AFTER DELETE ON country_group 
FOR EACH ROW
BEGIN
    DECLARE w FLOAT(5,2);
    DECLARE c INT;
    DECLARE s FLOAT(5,2);

    SET w = OLD.weight;
    SELECT count(*) into c FROM country_group WHERE code = OLD.code;

    SET s = w / c;
    UPDATE country_group SET weight = weight + s WHERE code = OLD.code;
END;

但是我得到这个错误:

Operation failed: There was an error while applying the SQL script to the database.
Executing:
DELETE FROM `extensionui2`.`country_group` WHERE `code`='ms' and`group_id`='9';

ERROR 1442: 1442: Can't update table 'country_group' in stored  function/trigger because it is already used by statement which invoked this stored function/trigger.
SQL Statement:
DELETE FROM `extensionui2`.`country_group` WHERE `code`='ms' and`group_id`='9'

我需要更改触发代码中的哪些内容才能使其正常工作?

MySQL 错误 1442 是由于 MySQL 中的 限制 。不允许触发器更新定义触发器的 table 中的任何行。

A stored function or trigger cannot modify a table that is already being used (for reading or writing) by the statement that invoked the function or trigger.

因此,不可能在触发器的上下文中执行您想执行的操作。