คำอธิบาย
ใช้ DELETE ... WHERE col1 = col2 เพื่อลบแถวที่ค่าของ 2 คอลัมน์เท่ากัน
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
Name varchar(40),
Score1 int,
Score2 int );
Query OK, 0 rows affected (2.71 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable values('John', 56, 76);
Query OK, 1 row affected (0.66 sec)
mysql> insert into DemoTable values('Chris', 77, 77);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('David', 89, 98);
Query OK, 1 row affected (0.13 sec)
แสดงข้อมูลก่อนลบ
mysql> select * from DemoTable;
ผลลัพธ์:
+-------+--------+--------+ | Name | Score1 | Score2 | +-------+--------+--------+ | John | 56 | 76 | | Chris | 77 | 77 | | David | 89 | 98 | +-------+--------+--------+ 3 rows in set (0.00 sec)
คิวรี่ DELETE ที่ Score1 = Score2
mysql> delete from DemoTable where Score1 = Score2; Query OK, 1 row affected (0.29 sec)
ตรวจสอบข้อมูลหลังลบ
mysql> select * from DemoTable;
ผลลัพธ์:
+-------+--------+--------+ | Name | Score1 | Score2 | +-------+--------+--------+ | John | 56 | 76 | | David | 89 | 98 | +-------+--------+--------+ 2 rows in set (0.00 sec)
คำอธิบาย
- Chris มี Score1=77, Score2=77 → เท่ากัน → ถูกลบ
- John (56≠76) และ David (89≠98) → คงอยู่
- 1 row affected ยืนยันลบ 1 แถว
ขยายความ: เงื่อนไขซับซ้อน
-- ลบถ้าคอลัมน์ใดคอลัมน์หนึ่งเท่ากัน DELETE FROM DemoTable WHERE Score1 = Score2 OR Score1 = Score3 OR Score2 = Score3; -- ลบถ้าทุกคอลัมน์เท่ากัน DELETE FROM DemoTable WHERE Score1 = Score2 AND Score2 = Score3;