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

时间:2015-02-01 20:40:29

标签: mysql triggers sql-update sql-delete

我有一个表country_group

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

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

例如,如果我删除权重为10.00的行,则表格应如下所示:

+------+----------+--------+
| 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'

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

1 个答案:

答案 0 :(得分:2)

MySQL ERROR 1442 是由MySQL中的限制引起的。触发器不允许更新定义触发器的表中的任何行。

  

存储的函数或触发器不能通过调用函数或触发器的语句修改已经使用(用于读取或写入)的表。

因此,在触发器的上下文中,你无法做你想做的事情。