在 MySQL 中添加列值时设置条件?
若要添加列值时设置条件,请使用 MySQL IF()。我们先创建一个表——
mysql> create table DemoTable -> ( -> Value1 int, -> Value2 int, -> Value3 int -> ); Query OK, 0 rows affected (0.64 sec)
使用 insert 命令向表中插入一些记录——
mysql> insert into DemoTable values(10,20,-30); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(50,60,90); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(100,200,400); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable values(30,40,-50); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable values(70,80,-1); Query OK, 1 row affected (0.24 sec)
使用 select 语句从表中显示所有记录——
mysql> 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)
这是在添加列值时设置条件的查询——
mysql> 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)
广告