Hàm FIELD(giatri, val1, val2, val3...) trả về vị trí của giá trị trong danh sách. Dùng trong ORDER BY để sắp xếp theo thứ tự tự định nghĩa.
Ví dụ
Tạo bảng StudentId: 100, 110, 90, 70, 120, 140
mysql> create table DemoTable (StudentId int); Query OK, 0 rows affected (0.58 sec)
Sắp xếp theo thứ tự: 100, 70, 140, 90, 120, 110
mysql> select *from DemoTable order by field(StudentId,'100','70','140','90','120','110');
+-----------+ | StudentId | +-----------+ | 100 | | 70 | | 140 | | 90 | | 120 | | 110 | +-----------+
Cơ chế: FIELD(StudentId, '100','70',...) trả về 1 cho 100, 2 cho 70, 3 cho 140... Giá trị không trong danh sách trả về 0 (xuất hiện đầu nếu ASC).
Ứng dụng: Sắp xếp trạng thái theo quy trình: 'pending'→'processing'→'shipped'→'delivered'→'cancelled'.
ORDER BY FIELD(status, 'pending','processing','shipped','delivered','cancelled')