为 MySQL 中的每个 SELECT 字段设置 WHERE 子句的替代方案
mysqlmysqli database更新于 2024/12/16 0:12:17
您可以使用 CASE 语句 −
mysql> create table DemoTable1988 ( Value1 int, Value2 int, Price int ); Query OK, 0 rows affected (0.64 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1988 values(10,7,500); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable1988 values(7,9,400); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1988 values(8,7,200); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1988 values(7,4,300); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1988;
这将产生以下输出 −
+--------+--------+-------+ | Value1 | Value2 | Price | +--------+--------+-------+ | 10 | 7 | 500 | | 7 | 9 | 400 | | 8 | 7 | 200 | | 7 | 4 | 300 | +--------+--------+-------+ 4 rows in set (0.00 sec)
这是对每个 SELECT 字段的 WHERE 子句的查询:
mysql> select sum( case when Value2=7 then Price else 0 end)- sum( case when Value1=7 then Price else 0 end) as Result from DemoTable1988;
这将产生以下输出 −
+--------+ | Result | +--------+ | 0 | +--------+ 1 row in set (0.23 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

