在MySQL中添加列值时设置条件?
要在添加列值时设置条件,请使用MySQLIF()。让我们首先创建一个表-
create table DemoTable -> ( -> Value1 int, -> Value2 int, -> Value3 int -> );
使用插入命令在表中插入一些记录-
insert into DemoTable values(10,20,-30); insert into DemoTable values(50,60,90); insert into DemoTable values(100,200,400); insert into DemoTable values(30,40,-50); insert into DemoTable values(70,80,-1);
使用select语句显示表中的所有记录-
select * from DemoTable;
这将产生以下输出-
+--------+--------+--------+ | Value1 | Value2 | Value3 | +--------+--------+--------+ | 10 | 20 | -30 | | 50 | 60 | 90 | | 100 | 200 | 400 | | 30 | 40 | -50 | | 70 | 80 | -1 | +--------+--------+--------+ 5 rows in set (0.00 sec)
这是在添加列值时设置条件的查询-
select Value1+Value2+if(Value3 > 0,Value3,0) from DemoTable;
这将产生以下输出-
+---------------------------------------+ | Value1+Value2+if(Value3 > 0,Value3,0) | +---------------------------------------+ | 30 | | 200 | | 700 | | 70 | | 150 | +---------------------------------------+ 5 rows in set (0.00 sec)