Kỹ thuật
Sử dụng biểu thức CASE WHEN trong SELECT để phân loại giá trị cột PageId thành "lẻ" hoặc "chẵn".
1. Tạo bảng
mysql> create table DemoTable (
PageId int
);
Query OK, 0 rows affected (0.85 sec)
2. Chèn dữ liệu
mysql> insert into DemoTable values(233),(34),(76),(89);
3. Xem dữ liệu
mysql> select * from DemoTable;
+--------+ | PageId | +--------+ | 233 | | 34 | | 76 | | 89 | +--------+ 4 rows in set (0.00 sec)
4. Truy vấn CASE WHEN
mysql> select PageId,
case when PageId % 2 != 0 then 'PageId is odd' else 'PageId is even' end as Result
from DemoTable;
Kết quả:
+--------+----------------+ | PageId | Result | +--------+----------------+ | 233 | PageId is odd | | 34 | PageId is even | | 76 | PageId is even | | 89 | PageId is odd | +--------+----------------+ 4 rows in set (0.00 sec)
Mẹo: Toán tử modulo % trả về phần dư. PageId % 2 != 0 nghĩa là lẻ.