Dùng FIELD() trong ORDER BY để giữ thứ tự như trong mảng IN.
Cú pháp:
select *from yourTableName where yourColumnName in(value1,value2,...) order by field(yourColumnName,value1,value2,...);
Tạo bảng OrderInDemo, chèn 6 bản ghi (Id: 90,9,10,1,3,2).
Truy vấn IN (10,1,3) mặc định sắp xếp theo Id:
mysql> select *from OrderInDemo where Id in(10,1,3);
Kết quả: 1,3,10 (sai thứ tự mong muốn).
Dùng FIELD():
mysql> select *from OrderInDemo OD where OD.Id in(10,1,3) -> order by field(OD.Id,10,1,3);
Kết quả đúng thứ tự 10,1,3:
+------+---------+------+ | Id | Name | Age | +------+---------+------+ | 10 | Carol | 19 | | 1 | John | 26 | | 3 | Johnson | 25 | +------+---------+------+ 3 rows in set (0.00 sec)