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

ใช้ CASE WHEN EXISTS ตรวจสอบมีแถวใน MySQL

รวม CASE WHEN กับ EXISTS (Subquery) เพื่อตรวจสอบว่ามีแถวตรงเงื่อนไขหรือไม่ แล้วคืนค่าข้อความ 'Present' หรือ 'Not Present'

ตัวอย่างการสร้างตาราง

mysql> create table DemoTable ( 
    UserId int, 
    UserName varchar(100) ); 
Query OK, 0 rows affected (0.57 sec)

เพิ่มข้อมูล 4 คน

mysql> insert into DemoTable values(100,'Chris'); 
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values(101,'Robert'); 
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(102,'David'); 
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values(103,'Mike'); 
Query OK, 1 row affected (0.11 sec)

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable;
+--------+----------+
| UserId | UserName |
+--------+----------+
| 100    | Chris    |
| 101    | Robert   |
| 102    | David    |
| 103    | Mike     |
+--------+----------+
4 rows in set (0.00 sec)

คำสั่ง CASE WHEN EXISTS ตรวจสอบ UserId = 102

mysql> select case when exists(select * from DemoTable where UserId = 102) 
then 'Present' else 'Not Present' end as Result;

ผลลัพธ์

+---------+
| Result  |
+---------+
| Present |
+---------+
1 row in set (0.02 sec)

คำอธิบาย:

  • EXISTS (Subquery) คืนค่า TRUE/FALSE เร็วกว่า COUNT(*) เพราะหยุดค้นหาที่เจอแถวแรก
  • CASE WHEN ... THEN ... ELSE ... END สร้างเงื่อนไข If-Else ใน SQL
  • สามารถนำไปใช้ใน SELECT, WHERE, ORDER BY ได้

ประยุกต์ใช้: สร้าง Flag column, รายงานสถานะ, Dynamic SQL ใน Application