ใช้ ORDER BY กับ CASE สำหรับการจัดเรียงเฉพาะเจาะจง
สร้างตารางและเพิ่มข้อมูล
mysql> create table DemoTable1610 ( Marks int, Name varchar(20) ); Query OK, 0 rows affected (0.51 sec)
mysql> insert into DemoTable1610 values(85,'John'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1610 values(78,'Carol'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1610 values(78,'John'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1610 values(85,'Carol'); Query OK, 1 row affected (0.20 sec)
คิวรี่จัดเรียง Marks น้อยไปมาก แล้ว Carol ก่อน John
mysql> select * from DemoTable1610 order by Marks, case when Name='Carol' then 1 else 0 end;
ผลลัพธ์
+-------+-------+ | Marks | Name | +-------+-------+ | 78 | John | | 78 | Carol | | 85 | John | | 85 | Carol | +-------+-------+ 4 rows in set (0.00 sec)
คำอธิบาย: เรียง Marks ASC ก่อน | ใน Marks เดียวกัน ใช้ CASE ให้ Carol=1, อื่นๆ=0 | เรียง CASE ASC ทำให้ 0 (John) อยู่ก่อน 1 (Carol) → John ก่อน Carol | หากต้องการ Carol ก่อน ให้ใช้ DESC หรือกลับเงื่อนไข