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

วิธี ORDER BY สองคอลัมน์ใน MySQL

รูปแบบคำสั่ง

ORDER BY yourColumnName1 ASC|DESC, yourColumnName2 ASC|DESC;

คอลัมน์แรกจัดอันดับก่อน (Primary Sort) คอลัมน์ที่สองใช้จัดอันดับเมื่อคอลัมน์แรกเท่ากัน

ตัวอย่าง

สร้างตารางและข้อมูล

mysql> create table OrderByDemo (StudentId int, StudentName varchar(100), StudentAge int);
mysql> insert into OrderByDemo values(1,'John',23),(3,'Johnson',24),(4,'Carol',26),(2,'David',20);

ASC, ASC (น้อยไปมาก ทั้งคู่)

mysql> select * from OrderByDemo order by StudentId ASC, StudentAge ASC;
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 1         | John        | 23         |
| 2         | David       | 20         |
| 3         | Johnson     | 24         |
| 4         | Carol       | 26         |
+-----------+-------------+------------+

DESC, DESC (มากไปน้อย ทั้งคู่)

mysql> select * from OrderByDemo order by StudentId DESC, StudentAge DESC;
+-----------+-------------+------------+
| StudentId | StudentName | StudentAge |
+-----------+-------------+------------+
| 4         | Carol       | 26         |
| 3         | Johnson     | 24         |
| 2         | David       | 20         |
| 1         | John        | 23         |
+-----------+-------------+------------+

สรุป

  • เรียงหลัก: StudentId
  • เรียงรอง: StudentAge (ใช้เมื่อ StudentId เท่ากัน)
  • ผสมได้: ORDER BY col1 ASC, col2 DESC