Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

MySQL: เรียงลำดับเฉพาะค่าก่อน (Custom ORDER BY)

การกำหนดลำดับแสดงผลแบบกำหนดเอง

ใช้ ORDER BY CASE WHEN ... THEN ... ELSE ... END เพื่อกำหนดให้ค่าเฉพาะขึ้นก่อน

ตัวอย่าง: ให้ค่าที่ขึ้นต้นด้วย 'smith' อยู่บนสุด

mysql> create table DemoTable808(Value varchar(100));
Query OK, 0 rows affected (0.61 sec)
mysql> insert into DemoTable808 values('smith');
mysql> insert into DemoTable808 values('Adamsmith');
mysql> insert into DemoTable808 values('Carolsmith');
mysql> insert into DemoTable808 values('smithJohn');

คำสั่ง ORDER BY แบบกำหนดเอง

mysql> select * from DemoTable808 
order by case when Value like 'smith%' then 0 else 1 end asc, Value asc;

ผลลัพธ์:

+------------+
| Value      |
+------------+
| smith      |
| smithJohn  |
| Adamsmith  |
| Carolsmith |
+------------+

คำอธิบาย

  • CASE WHEN Value LIKE 'smith%' THEN 0 ELSE 1 END - ให้คะแนน 0 กับค่าที่ขึ้นต้น smith, 1 กับที่เหลือ
  • ASC - เรียง 0 ก่อน 1 (ค่าที่ต้องการอยู่บน)
  • , Value ASC - เรียงรองภายในกลุ่มเดียวกัน

วิธีที่ 2: ใช้ FIELD() (สำหรับค่าเฉพาะเจาะจง)

ORDER BY FIELD(Value, 'smith', 'smithJohn', 'Adamsmith', 'Carolsmith')

สรุป

ใช้ CASE WHEN สำหรับเงื่อนไขแบบ Pattern (LIKE), ใช้ FIELD() สำหรับรายการค่าที่แน่นอน