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

ฟังก์ชัน IF() ในคำสั่ง SELECT ของ MySQL

IF() คืนค่าตามเงื่อนไข: IF(condition, true_value, false_value)

ตัวอย่าง

mysql> create table DemoTable ( Value int );
Query OK, 0 rows affected (0.60 sec)
mysql> insert into DemoTable values(1000); Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(2000); Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(500);  Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values(1100); Query OK, 1 row affected (0.16 sec)

ใช้ IF() ใน SELECT

mysql> select Value, IF(Value > 1000, CONCAT(Value,' is greater than 1000'), CONCAT(Value,' is lower than 1000')) AS Result from DemoTable;

ผลลัพธ์

+-------+---------------------------+
| Value | Result                    |
+-------+---------------------------+
| 1000  | 1000 is lower than 1000   |
| 2000  | 2000 is greater than 1000 |
| 500   | 500 is lower than 1000    |
| 1100  | 1100 is greater than 1000 |
+-------+---------------------------+

ใช้สร้างคอลัมน์คำนวณหรือแสดงข้อความตามเงื่อนไขได้อย่างยืดหยุ่น