为MySQL中的每个SELECT字段设置WHERE子句的替代项
您可以使用CASE语句-
mysql> create table DemoTable1988 ( Value1 int, Value2 int, Price int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1988 values(10,7,500); mysql> insert into DemoTable1988 values(7,9,400); mysql> insert into DemoTable1988 values(8,7,200); mysql> insert into DemoTable1988 values(7,4,300);
使用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)
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志