ใช้ฟังก์ชัน RIGHT(column, 3) ใน ORDER BY เพื่อเรียงตาม 3 ตัวอักษรสุดท้าย
ไวยากรณ์
SELECT * FROM yourTableName ORDER BY RIGHT(yourColumnName, 3) ASC|DESC;
ตัวอย่างการใช้งาน
สร้างตาราง OrderByLast3Chars:
mysql> CREATE TABLE OrderByLast3Chars (
-> EmployeeId INT NOT NULL AUTO_INCREMENT,
-> EmployeeName VARCHAR(20),
-> EmployeeAge INT,
-> PRIMARY KEY(EmployeeId)
-> );
เพิ่มข้อมูล (ชื่อลงท้ายด้วยตัวเลข 3 หลัก):
mysql> INSERT INTO OrderByLast3Chars(EmployeeName, EmployeeAge) VALUES('Carol_901',24);
mysql> INSERT INTO OrderByLast3Chars(EmployeeName, EmployeeAge) VALUES('Bob_101',21);
mysql> INSERT INTO OrderByLast3Chars(EmployeeName, EmployeeAge) VALUES('Sam_107',22);
mysql> INSERT INTO OrderByLast3Chars(EmployeeName, EmployeeAge) VALUES('Mile_677',26);
mysql> INSERT INTO OrderByLast3Chars(EmployeeName, EmployeeAge) VALUES('John_978',27);
mysql> INSERT INTO OrderByLast3Chars(EmployeeName, EmployeeAge) VALUES('David_876',29);
ข้อมูลเดิม
+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | Carol_901 | 24 | | 2 | Bob_101 | 21 | | 3 | Sam_107 | 22 | | 4 | Mile_677 | 26 | | 5 | John_978 | 27 | | 6 | David_876 | 29 | +------------+--------------+-------------+
กรณี 1: เรียง 3 ตัวท้าย น้อยไปมาก (ASC)
mysql> SELECT * FROM OrderByLast3Chars ORDER BY RIGHT(EmployeeName, 3) ASC;
+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | Carol_901 | 24 | | 2 | Bob_101 | 21 | | 3 | Sam_107 | 22 | | 4 | Mile_677 | 26 | | 5 | John_978 | 27 | | 6 | David_876 | 29 | +------------+--------------+-------------+
กรณี 2: เรียง 3 ตัวท้าย มากไปน้อย (DESC)
mysql> SELECT * FROM OrderByLast3Chars ORDER BY RIGHT(EmployeeName, 3) DESC;
+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 5 | John_978 | 27 | | 1 | Carol_901 | 24 | | 6 | David_876 | 29 | | 4 | Mile_677 | 26 | | 3 | Sam_107 | 22 | | 2 | Bob_101 | 21 | +------------+--------------+-------------+