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

จัดเรียง MySQL: ใส่ค่าเฉพาะด้านบน แล้วค่อยเรียงวันที่สำหรับที่เหลือ

ใช้ ORDER BY column = 'value' DESC, date_column เพื่อจัดให้แถวที่ตรงค่าเฉพาะอยู่บนสุด แล้วค่อยเรียงส่วนที่เหลือตามวันที่

Syntax

SELECT * FROM table_name 
ORDER BY (column_name = 'target_value') DESC, date_column;
  • (column = 'value') คืนค่า 1 (True) หรือ 0 (False)
  • DESC ให้ True (1) อยู่บนสุด
  • ส่วนที่เป็น False (0) จะเรียงตาม date_column (ASC โดยค่าเริ่มต้น)

ตัวอย่างการใช้งาน

1. สร้างตารางและเพิ่มข้อมูล

mysql> create table DemoTable1932 ( UserName varchar(20), ShippingDate date ); Query OK, 0 rows affected (0.00 sec)

mysql> insert into DemoTable1932 values('Chris','2018-10-12'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1932 values('David','2019-04-11'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1932 values('Mike','2016-12-04'); Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1932 values('Carol','2017-12-26'); Query OK, 1 row affected (0.00 sec)

ข้อมูลทั้งหมด:

mysql> select * from DemoTable1932;
+----------+--------------+
| UserName | ShippingDate |
+----------+--------------+
| Chris    | 2018-10-12   |
| David    | 2019-04-11   |
| Mike     | 2016-12-04   |
| Carol    | 2017-12-26   |
+----------+--------------+
4 rows in set (0.00 sec)

2. ใส่ David บนสุด แล้วค่อยเรียง ShippingDate ASC

mysql> select * from DemoTable1932 
    -> order by UserName = 'David' desc, ShippingDate;

ผลลัพธ์:

+----------+--------------+
| UserName | ShippingDate |
+----------+--------------+
| David    | 2019-04-11   |  ← Priority 1 (True=1)
| Mike     | 2016-12-04   |  ← Priority 0, เรียงวันที่ ASC
| Carol    | 2017-12-26   |
| Chris    | 2018-10-12   |
+----------+--------------+
4 rows in set (0.00 sec)

การประยุกต์ใช้หลาย Priority Levels

ORDER BY 
    (status = 'Urgent') DESC,      -- Priority 1: Urgent บนสุด
    (status = 'High') DESC,        -- Priority 2: High ต่อมา
    (priority = 1) DESC,           -- Priority 3: priority=1
    created_at ASC;                -- ที่เหลือ เรียงวันที่เก่าไปใหม่

ใช้ FIELD() สำหรับหลายค่า (MySQL Specific)

ORDER BY FIELD(UserName, 'David', 'Admin', 'Manager') DESC, ShippingDate;
  • FIELD(str, val1, val2, ...) คืน Index (1-based) ของค่าที่ตรง 0 ถ้าไม่ตรง
  • DESC ให้ค่าที่เจอ (Index > 0) อยู่บน

⚠️ Performance Note

ORDER BY (col = 'val') DESC ไม่สามารถใช้ Index สำหรับ Sorting ได้ (Non-SARGable) ตารางใหญ่ควรพิจารณา:

  • เพิ่ม Priority Column (TINYINT) แล้ว Index
  • UNION: (SELECT * FROM t WHERE col='val') UNION ALL (SELECT * FROM t WHERE col!='val' ORDER BY date)

สรุป: ใช้ ORDER BY (col = 'value') DESC, date_col เพื่อ Priority Sort: ค่าเป้าหมายบนสุด ที่เหลือเรียงวันที่ ใช้ FIELD() สำหรับหลาย Priority