คำสั่งหลัก
ใช้ ROW_COUNT() ทันทีหลังคำสั่ง DELETE/UPDATE/INSERT เพื่อดูจำนวนแถวที่ได้รับผลกระทบ
รูปแบบคำสั่ง
DELETE FROM table WHERE condition; SELECT ROW_COUNT();
ตัวอย่างครบถ้วน
1. สร้างตารางลูกค้า
mysql> create table rowAfftectedByDeleteDemo
-> (
-> CustomerId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> CustomerName varchar(20)
-> );
Query OK, 0 rows affected (0.86 sec)
2. เพิ่มข้อมูล 8 แถว
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Bob');
Query OK, 1 row affected (0.09 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Sam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('David');
Query OK, 1 row affected (0.08 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Maxwell');
Query OK, 1 row affected (0.09 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('Ramit');
Query OK, 1 row affected (0.08 sec)
mysql> insert into rowAfftectedByDeleteDemo(CustomerName) values('James');
Query OK, 1 row affected (0.10 sec)
3. ดูข้อมูลทั้งหมด
mysql> select * from rowAfftectedByDeleteDemo;
+------------+--------------+ | CustomerId | CustomerName | +------------+--------------+ | 1 | John | | 2 | Carol | | 3 | Bob | | 4 | Sam | | 5 | David | | 6 | Maxwell | | 7 | Ramit | | 8 | James | +------------+--------------+
4. ROW_COUNT() ก่อน DELETE (คือ -1)
mysql> select row_count();
+-------------+ | row_count() | +-------------+ | -1 | +-------------+
-1 = คำสั่งก่อนหน้าไม่ใช่ DML (SELECT ไม่เปลี่ยนแปลงแถว)
5. DELETE หลายแถว
mysql> delete from rowAfftectedByDeleteDemo
-> where CustomerId = 3 || CustomerId = 4 || CustomerId = 5 || CustomerId = 6;
Query OK, 4 rows affected (0.13 sec)
6. ROW_COUNT() หลัง DELETE (คือ 4)
mysql> select row_count();
+-------------+ | row_count() | +-------------+ | 4 | +-------------+
ROW_COUNT() กับคำสั่งอื่น
| คำสั่ง | ROW_COUNT() คืนค่า |
|---|---|
| INSERT | จำนวนแถวที่ insert สำเร็จ |
| UPDATE | จำนวนแถวที่เปลี่ยนแปลงจริง (matched ≠ changed) |
| DELETE | จำนวนแถวที่ลบ |
| REPLACE | จำนวนแถวที่แทนที่ (delete+insert = 2) |
| LOAD DATA | จำนวนแถวที่โหลด |
| SELECT | -1 (ไม่ใช่ DML) |
ใน Application (PHP, Python, etc.)
-- PHP PDO
$stmt = $pdo->exec("DELETE FROM table WHERE id > 100");
echo "Deleted: " . $stmt->rowCount();
-- Python MySQL Connector
cursor.execute("DELETE FROM table WHERE id > 100")
print("Deleted:", cursor.rowcount)
MySQL 8.0: Information Schema
SELECT TABLE_ROWS FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'db' AND TABLE_NAME = 'table';
(ประมาณการ ไม่ใช่ real-time)
สรุป: ROW_COUNT() ทันทีหลัง DML = วิธีมาตรฐานดู affected rows ใน MySQL client