Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Cách sắp xếp nhiều cột trong một truy vấn MySQL


Có thể sắp xếp nhiều cột trong một truy vấn bằng cách liệt kê nhiều tên cột sau ORDER BY.

Cú pháp

Select Col1,Col2,... from table_name ORDER BY Col1, Col2,...

Ví dụ

Sắp xếp bảng Student theo Name và RollNo:

mysql> Select Name, RollNo from student order by name,rollno;
+--------+--------+
| name   | rollno |
+--------+--------+
| Aarav  |    150 |
| Aryan  |    165 |
| Gaurav |    100 |
+--------+--------+

Cũng có thể lấy tất cả cột:

mysql> Select * from student order by name,rollno;
+--------+--------+--------+
| Name   | RollNo | Grade  |
+--------+--------+--------+
| Aarav  |    150 | M.SC   |
| Aryan  |    165 | M.tech |
| Gaurav |    100 | B.tech |
+--------+--------+--------+

Giải thích: Sắp xếp trước theo name, nếu trùng thì theo rollno. Mỗi cột có thể thêm ASC/DESC riêng: ORDER BY name ASC, rollno DESC.