Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การทำงานของ FOR EACH ROW ใน MySQL Trigger


FOR EACH ROW หมายถึง trigger จะทำงาน **ต่อแต่ละแถวที่ได้รับผลกระทบ** (updated หรือ deleted) ไม่ใช่ทำงานต่อทุกแถวในตาราง ตัวอย่างสาธิต:

ตัวอย่าง

สร้างตาราง Sample และ Sample_rowaffected แล้วสร้าง trigger BEFORE DELETE นับจำนวนแถวที่ลบ:

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)
mysql> Create table Sample_rowaffected(id int);
Query OK, 0 rows affected (0.53 sec)
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 ;

ลบแถวที่ id >= 500 (2 แถว):

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 พบ 2 แถว สอดคล้องกับจำนวนแถวที่ลบ:

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

สรุป: FOR EACH ROW ทำงานต่อแต่ละแถวที่ **ตรงเงื่อนไขและถูกกระทบ**