สร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable1986 ( Number int );
mysql> insert into DemoTable1986 values(50); mysql> insert into DemoTable1986 values(60); mysql> insert into DemoTable1986 values(100); mysql> insert into DemoTable1986 values(200); mysql> insert into DemoTable1986 values(350);
ข้อมูลทั้งหมด
+--------+ | Number | +--------+ | 50 | | 60 | | 100 | | 200 | | 350 | +--------+
Query กรองด้วย IN() และเรียงตามลำดับที่กำหนด
mysql> select * from DemoTable1986 where Number IN(50,100,350) order by field(Number,350,100,50);
ผลลัพธ์
+--------+ | Number | +--------+ | 350 | | 100 | | 50 | +--------+
อธิบาย
IN(50,100,350)กรองเฉพาะค่าที่อยู่ในรายการFIELD(Number, 350, 100, 50)คืนค่าตำแหน่งของ Number ในรายการ: 350→1, 100→2, 50→3ORDER BY FIELD(...)เรียงตามตำแหน่งที่ได้ (1, 2, 3) → 350, 100, 50
ฟังก์ชัน FIELD()
FIELD(str, str1, str2, str3, ...) -- คืนค่า Index (1-based) ของ str ในรายการ str1, str2, ... -- คืนค่า 0 ถ้าไม่พบ
ตัวอย่างการใช้ FIELD กับ STRING
SELECT * FROM products
WHERE category IN ('Electronics', 'Clothing', 'Books')
ORDER BY FIELD(category, 'Electronics', 'Books', 'Clothing');
เทคนิคเก่าที่ไม่แนะนำ (CASE WHEN)
ORDER BY CASE Number WHEN 350 THEN 1 WHEN 100 THEN 2 WHEN 50 THEN 3 ELSE 4 END
FIELD() อ่านง่ายกว่าและประสิทธิภาพดีกว่า