为此,请IF()
在MySQL中使用。语法如下-
select IF(yourColumnName1=0,yourColumnName2,yourColumnName1) as anyAliasName from yourTableName;
让我们创建一个表-
mysql> create table demo30 −> ( −> id int not null auto_increment primary key, −> value int, −> original_value int −> ) −> ;
借助insert命令将一些记录插入表中-
mysql> insert into demo30(value,original_value) values(50,10); mysql> insert into demo30(value,original_value) values(1000,0); mysql> insert into demo30(value,original_value) values(0,40); mysql> insert into demo30(value,original_value) values(30,0);
使用select语句显示表中的记录-
mysql> select *from demo30;
这将产生以下输出-
+----+-------+----------------+ | id | value | original_value | +----+-------+----------------+ | 1 | 50 | 10 | | 2 | 1000 | 0 | | 3 | 0 | 40 | | 4 | 30 | 0 | +----+-------+----------------+ 4 rows in set (0.00 sec)
以下是在MySQL中如果选定值为'0'的情况下要从另一列中选择的查询-
mysql> select id, if(original_value= 0,value,original_value) as Result −> from demo30;
这将产生以下输出-
+----+--------+ | id | Result | +----+--------+ | 1 | 10 | | 2 | 1000 | | 3 | 40 | | 4 | 30 | +----+--------+ 4 rows in set (0.00 sec)