FOR EACH ROW
significa para cada una de las filas coincidentes que se actualiza o eliminado .
El cuerpo del disparador no recorrerá los datos de la tabla completa a menos que haya una condición donde en la consulta.
A continuación se muestra un ejemplo de trabajo:
Crear tablas de muestra :
drop table if exists tbl_so_q23374151;
create table tbl_so_q23374151 ( i int, v varchar(10) );
-- set test data
insert into tbl_so_q23374151
values (1,'one'),(2,'two' ),(3,'three'),(10,'ten'),(11,'eleven');
-- see current data in table**:
select * from tbl_so_q23374151;
+------+--------+
| i | v |
+------+--------+
| 1 | one |
| 2 | two |
| 3 | three |
| 10 | ten |
| 11 | eleven |
+------+--------+
5 rows in set (0.00 sec)
Tabla de muestra para registrar el recuento de bucles en el cuerpo del disparador :
-- let us record, loop count of trigger, in a table
drop table if exists tbl_so_q23374151_rows_affected;
create table tbl_so_q23374151_rows_affected( i int );
select count(*) as rows_affected from tbl_so_q23374151_rows_affected;
+---------------+
| rows_affected |
+---------------+
| 0 |
+---------------+
Definir una eliminación disparador :
drop trigger if exists trig_bef_del_on_tbl_so_q23374151;
delimiter //
create trigger trig_bef_del_on_tbl_so_q23374151 before delete on tbl_so_q23374151
for each row begin
set @cnt = if(@cnt is null, 1, (@cnt+1));
/* for cross checking save loop count */
insert into tbl_so_q23374151_rows_affected values ( @cnt );
end;
//
delimiter ;
Ahora, pruebe una eliminación operación :
delete from tbl_so_q23374151 where i like '%1%';
-- now let us see what the loop count was
select @cnt as 'cnt';
+------+
| cnt |
+------+
| 3 |
+------+
Ahora, comprueba el efecto de activación en la tabla principal :
-- now let us see the table data
select * from tbl_so_q23374151;
+------+-------+
| i | v |
+------+-------+
| 2 | two |
| 3 | three |
+------+-------+
2 rows in set (0.00 sec)
select count(*) as rows_affected from tbl_so_q23374151_rows_affected;
+---------------+
| rows_affected |
+---------------+
| 3 |
+---------------+
1 row in set (0.00 sec)