IF() 函式在 MySQL Select 語句中?
IF() 函式會根據某條件返回一個值。
語法如下−
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)
使用 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)
使用 select 語句從表中顯示所有記錄 −
mysql> select *from DemoTable;
這會產生以下輸出 −
+-------+ | Value | +-------+ | 1000 | | 2000 | | 500 | | 1100 | +-------+ 4 rows in set (0.00 sec)
可以在 MySQL 中實現 IF() 的查詢如下 −
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 | +-------+---------------------------+ 4 rows in set (0.00 sec)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP