根据 MySQL 中的列值在 SELECT 中执行乘法?
你可以为此使用 CASE 语句。让我们首先创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Value1 int, Value2 int ); Query OK, 0 rows affected (0.76 sec)
使用 insert 命令在表中插入一些记录 -
mysql> insert into DemoTable(Value1,Value2) values(10,5); Query OK, 1 row affected (0.09 sec) mysql> insert into DemoTable(Value1,Value2) values(20,0); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(Value1,Value2) values(40,10); Query OK, 1 row affected (0.28 sec) mysql> insert into DemoTable(Value1,Value2) values(50,0); Query OK, 1 row affected (0.12 sec)
使用 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)
广告