‘FOR EACH ROW’在 MySQL 触发器中是如何工作的?


实际上“FOR EACH ROW”表示针对每个匹配的行,无论是被更新还是被删除。换句话说,我们可以说触发器不适用于每一行,它只是说针对每个受影响的表行执行触发器主体。我们可以通过下面的示例来说明这一点 −

示例

在此示例中,我们创建了两个表,Sample 和 Sample_rowaffected,如下所示 −

mysql> Create table Sample(id int, value varchar(20));
Query OK, 0 rows affected (0.47 sec)

mysql> Insert into Sample(id, value) values(100, 'same'),(101,
'Different'),(500, 'excellent'),(501, 'temporary');
Query OK, 4 rows affected (0.04 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> Select * from Sample;
+------+-----------+
| id   | value     |
+------+-----------+
| 100  | same      |
| 101  | Different |
| 500  | excellent |
| 501  | temporary |
+------+-----------+
4 rows in set (0.00 sec)

mysql> Create table Sample_rowaffected(id int);
Query OK, 0 rows affected (0.53 sec)

mysql> Select Count(*) as ‘Rows Affected’ from sample_rowaffected;
+---------------+
| Rows Affected |
+---------------+
|             0 |
+---------------+
1 row in set (0.10 sec)

现在,我们将创建一个触发器,在表“Sample”中删除任何值之前触发,如下所示 −

mysql> Delimiter //
mysql> Create trigger trigger_before_delete_sample BEFORE DELETE on
Sample
    -> FOR EACH ROW
    -> BEGIN
    -> SET @count = if (@count IS NULL, 1, (@count+1));
    -> INSERT INTO sample_rowaffected values (@count);
    -> END ;
    -> //
Query OK, 0 rows affected (0.15 sec)
mysql> Delimiter ;

现在,下面的查询将从表“Sample”中删除一些值,并且删除的行数将存储在 @count 用户变量中 −

mysql> Delete from Sample WHERE ID >=500;
Query OK, 2 rows affected (0.11 sec)

mysql> Select @count;
+--------+
| @count |
+--------+
|      2 |
+--------+
1 row in set (0.03 sec)

借助下面的查询,我们可以检查受删除影响的行值,如下所示,这些行值插入到了 sample_rowaffected 表中 −

mysql> Select Count(*) as 'Rows Affected' from sample_rowaffected;
+---------------+
| Rows Affected |
+---------------+
|             2 |
+---------------+
1 row in set (0.00 sec)

mysql> Select * from Sample;
+------+-----------+
| id   | value     |
+------+-----------+
| 100  | same      |
| 101  | Different |
+------+-----------+
2 rows in set (0.00 sec)

借助上面的示例,我们清楚地知道“FOR EACH ROW”表示针对每个匹配的行,无论是被更新还是被删除。

更新日期: 2020 年 6 月 22 日

5K+ 浏览量

开启你的 职业 生涯

完成课程以获得认证

开始学习
广告