将 IF 语句插入到 MySQL 查询的正确方式是什么?
要将 IF 语句插入到 MySQL 查询中,请使用以下语法:
select yourColumnName ,if(yourCondition, yourStatement1,yourStatement2) from yourTableName;
让我们先创建一个表 −
mysql> create table DemoTable1571 -> ( -> Id int, -> Value int -> ); Query OK, 0 rows affected (5.63 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1571 values(101,500); Query OK, 1 row affected (1.07 sec) mysql> insert into DemoTable1571 values(102,450); Query OK, 1 row affected (0.47 sec) mysql> insert into DemoTable1571 values(103,300); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1571 values(104,700); Query OK, 1 row affected (0.23 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1571;
这将产生以下输出
+------+-------+ | Id | Value | +------+-------+ | 101 | 500 | | 102 | 450 | | 103 | 300 | | 104 | 700 | +------+-------+ 4 rows in set (0.00 sec)
下面是将 if 语句正确插入到 MySQL 查询中的查询。
mysql> select Value,if(Value > 550, 'Value is greater than 550','Value is less than 550') from DemoTable1571;
这将产生以下输出 −
+-------+-----------------------------------------------------------------------+ | Value | if(Value > 550, 'Value is greater than 550','Value is less than 550') | +-------+-----------------------------------------------------------------------+ | 500 | Value is less than 550 | | 450 | Value is less than 550 | | 300 | Value is less than 550 | | 700 | Value is greater than 550 | +-------+-----------------------------------------------------------------------+ 4 rows in set (0.00 sec)
广告