如果在MySQL中字段值> 0,如何减去1?
您可以为此使用CASE语句和UPDATE命令。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value int );
使用插入命令在表中插入记录-
mysql> insert into DemoTable(Value) values(100); mysql> insert into DemoTable(Value) values(0); mysql> insert into DemoTable(Value) values(104); mysql> insert into DemoTable(Value) values(0); mysql> insert into DemoTable(Value) values(5); mysql> insert into DemoTable(Value) values(10); mysql> insert into DemoTable(Value) values(0);
使用选择命令显示表中的记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-------+ | Id | Value | +----+-------+ | 1 | 100 | | 2 | 0 | | 3 | 104 | | 4 | 0 | | 5 | 5 | | 6 | 10 | | 7 | 0 | +----+-------+ 7 rows in set (0.00 sec)
现在使用设置条件,如果字段值>0,则减去字段值大于0,否则让它保持不变-
mysql> update DemoTable set Value=CASE WHEN Value > 0 THEN Value-1 ELSE 0 END; Rows matched: 7 Changed: 4 Warnings: 0
让我们再次检查表记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+-------+ | Id | Value | +----+-------+ | 1 | 99 | | 2 | 0 | | 3 | 103 | | 4 | 0 | | 5 | 4 | | 6 | 9 | | 7 | 0 | +----+-------+ 7 rows in set (0.00 sec)