Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Thay thế WHERE clause cho từng cột SELECT bằng CASE trong MySQL


Sử dụng CASE statement. Tạo bảng:

mysql> create table DemoTable1988 ( Value1 int, Value2 int, Price int ); Query OK, 0 rows affected (0.64 sec)

Thêm dữ liệu:

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)

Hiển thị dữ liệu:

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)

Truy vấn dùng CASE để tổng Price khi Value2=7 trừ tổng Price khi Value1=7:

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;

Kết quả:

+--------+
| Result |
+--------+
| 0      |
+--------+
1 row in set (0.23 sec)