mysql - 创建触发器以对同一个表进行条件更新

标签 mysql

 delimiter //
 create trigger T1 before update on account
     for each row
        if NEW.balance <= 0 then
          update account set balance=OLD.balance;
       end if;
     //
Query OK, 0 rows affected (0.09 sec)

 delimiter ;
 update account set balance=-1 where id=101;

ERROR 1442 (HY000): Can't update table 'account' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.

最佳答案

MySQL 使用行级触发器,因此针对正在更改的每一行都会触发触发器。因此没有理由更新目标表,只需分配值:

create trigger T1 before update on account
 for each row
    if NEW.balance <= 0 then
      set new.balance = OLD.balance; -- this is the difference
   end if;

SQLFiddle 示例:http://sqlfiddle.com/#!2/34aebb/1

<小时/>

您的更新无论如何都不会起作用,因为它缺少 where 子句,这意味着您将仅因为更改了一行就更新了整个表。

关于mysql - 创建触发器以对同一个表进行条件更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745073/

相关文章:

php - 当 2 个 MySQL 连接使用相同的临时表名时,它们是否可能崩溃?

mysql - 创建外键约束时出现语法错误

php - 限制表单提交率

mysql - 使用联接对大型用户数据库进行分页

mysql - OCaml - ocaml-mysql 的时间戳字段异常

来自同一表中其他列的 MySQL 更新列

php - 在提出内存问题之前,php 数组可以有多大?

mysql - postgres 计数或求和忽略脏东西

php - 如何在MYSQL中删除和插入序列号以及重新排序序列号?

mysql - 如何从表消息和查看的消息创建 "Read Message"查询?