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

วิธีจัดเรียงข้อมูลตามลำดับที่กำหนดเองใน MySQL

การจัดเรียงข้อมูลตามลำดับเฉพาะด้วย ORDER BY IF()

เมื่อต้องการเรียงลำดับข้อมูลไม่ใช่ตามค่า ASC/DESC ธรรมดา แต ตามลำดับที่ผู้ใช้กำหนดเอง สามารถใช้ ORDER BY IF() ได้ วิธีนี้เหมาะสำหรับการจัดอันดับหรือแสดงผลตามความสำคัญที่กำหนดล่วงหน้า

ไวยากรณ์ (Syntax)

SELECT * FROM yourTableName 
ORDER BY IF(yourColumnName=yourValue1 OR yourColumnName=yourValue2 OR yourColumnName=yourValue3, yourColumnName, ~yourColumnName) ASC;

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

สร้างตารางนักเรียน:

mysql> CREATE TABLE arrangeDataInSpecificOrder (
    -> StudentId INT,
    -> StudentName VARCHAR(20)
    -> );
Query OK, 0 rows affected (0.64 sec)

เพิ่มข้อมูล:

mysql> INSERT INTO arrangeDataInSpecificOrder VALUES(10,'Larry');
Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO arrangeDataInSpecificOrder VALUES(15,'Mike');
Query OK, 1 row affected (0.09 sec)
mysql> INSERT INTO arrangeDataInSpecificOrder VALUES(100,'Sam');
Query OK, 1 row affected (0.16 sec)
mysql> INSERT INTO arrangeDataInSpecificOrder VALUES(70,'Carol');
Query OK, 1 row affected (0.12 sec)
mysql> INSERT INTO arrangeDataInSpecificOrder VALUES(90,'Bob');
Query OK, 1 row affected (0.14 sec)
mysql> INSERT INTO arrangeDataInSpecificOrder VALUES(300,'David');
Query OK, 1 row affected (0.12 sec)

ข้อมูลก่อนเรียงลำดับ:

mysql> SELECT * FROM arrangeDataInSpecificOrder;
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10        | Larry       |
| 15        | Mike        |
| 100       | Sam         |
| 70        | Carol       |
| 90        | Bob         |
| 300       | David       |
+-----------+-------------+
6 rows in set (0.00 sec)

เรียงลำดับตาม StudentId ที่ระบุ (300, 100, 10) ก่อน ตามด้วยค่าอื่น:

mysql> SELECT * FROM arrangeDataInSpecificOrder 
    -> ORDER BY IF(StudentId=300 OR StudentId=100 OR StudentId=10, StudentId, ~StudentId) ASC;

ผลลัพธ์:

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10        | Larry       |
| 100       | Sam         |
| 300       | David       |
| 90        | Bob         |
| 70        | Carol       |
| 15        | Mike        |
+-----------+-------------+
6 rows in set (0.00 sec)

คำอธิบาย

ฟังก์ชัน IF() จะตรวจสอบว่า StudentId อยู่ในรายการที่กำหนด (300, 100, 10) หรือไม่ ถ้าอยู่จะคืนค่า StudentId จริง (เรียงจากน้อยไปมาก) ถ้าไม่อยู่จะคืนค่า ~StudentId (bitwise NOT) ทำให้ค่าที่ไม่อยู่ในรายการถูกส่งไปท้ายสุด วิธีนี้ยืดหยุ่นกว่า FIELD() และใช้ได้กับเงื่อนไขซับซ้อน