Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Hàm IF() trong câu lệnh SELECT MySQL?

Hàm IF() trả về một giá trị dựa trên một điều kiện.

Cú pháp như sau:

SELECT IF(yourCondition, yourMessageIfConditionBecomesTrue, yourMessageIfConditionBecomesFalse) from yourTableName; Let us first create a table: mysql> create table DemoTable ( Value int ); Query OK, 0 rows affected (0.60 sec)

Chèn các bản ghi vào bảng bằng lệnh insert:

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)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select:

mysql> select * from DemoTable;

Điều này sẽ tạo ra đầu ra sau:

+-------+
| Value |
+-------+
| 1000  |
| 2000  |
| 500   |
| 1100  |
+-------+
4 rows in set (0.00 sec)

Đây là truy vấn để triển khai IF() trong MySQL:

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

Điều này sẽ tạo ra đầu ra sau:

+-------+---------------------------+
| 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 |
+-------+---------------------------+
4 rows in set (0.00 sec)