根据MySQL中的列值在SELECT中执行乘法?
您可以为此使用CASE语句。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value1 int, Value2 int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(Value1,Value2) values(10,5); mysql> insert into DemoTable(Value1,Value2) values(20,0); mysql> insert into DemoTable(Value1,Value2) values(40,10); mysql> insert into DemoTable(Value1,Value2) values(50,0);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+--------+--------+ | Id | Value1 | Value2 | +----+--------+--------+ | 1 | 10 | 5 | | 2 | 20 | 0 | | 3 | 40 | 10 | | 4 | 50 | 0 | +----+--------+--------+ 4 rows in set (0.00 sec)
以下是根据列值在SELECT中执行乘法的查询-
mysql> select Value1,Value2, case when Value2 > 0 then Value1*Value2 else 0 end as Multiplication from DemoTable;
这将产生以下输出-
+--------+--------+----------------+ | Value1 | Value2 | Multiplication | +--------+--------+----------------+ | 10 | 5 | 50 | | 20 | 0 | 0 | | 40 | 10 | 400 | | 50 | 0 | 0 | +--------+--------+----------------+ 4 rows in set (0.00 sec)