MySQL Select 语句中的 IF() 函数?
该IF()函数根据条件返回一个值。
语法如下:
SELECT IF(yourCondition, yourMessageIfConditionBecomesTrue,yourMessageIfConditionBecomesFalse) from yourTableName; Let us first create a table: mysql> create table DemoTable ( Value int );
使用插入命令在表中插入记录-
mysql> insert into DemoTable values(1000); mysql> insert into DemoTable values(2000); mysql> insert into DemoTable values(500); mysql> insert into DemoTable values(1100);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+-------+ | Value | +-------+ | 1000 | | 2000 | | 500 | | 1100 | +-------+ 4 rows in set (0.00 sec)
这是IF()在MySQL中实现的查询-
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)