Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

MySQL에서 한 번에 둘 이상의 열을 정렬하는 방법은 무엇입니까?

<시간/>

한 번에 둘 이상의 열을 정렬하려면 ORDER BY 절을 사용할 수 있습니다. 다음은 구문입니다 -

select yourColumnName1,yourColumnName2,yourColumnName3 from yourTableName
order by yourColumnName2,yourColumnName3;

먼저 테이블을 생성하겠습니다 -

mysql> create table doubleSortDemo
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100),
   -> StudentCountryName varchar(10)
   -> );
Query OK, 0 rows affected (0.71 sec)

다음은 삽입 명령을 사용하여 테이블에 레코드를 삽입하는 쿼리입니다 -

mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('John','AUS');
Query OK, 1 row affected (0.21 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Sam','UK');
Query OK, 1 row affected (0.20 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Bob','US');
Query OK, 1 row affected (0.16 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Carol','UK');
Query OK, 1 row affected (0.32 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName)
values('David','AUS');
Query OK, 1 row affected (0.19 sec)
mysql> insert into doubleSortDemo(StudentName,StudentCountryName) values('Larry','UK');
Query OK, 1 row affected (0.15 sec)

다음은 select 문을 사용하여 테이블의 모든 레코드를 표시하는 쿼리입니다 -

mysql> select * from doubleSortDemo;

이것은 다음과 같은 출력을 생성합니다 -

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 1         | John        | AUS                |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
| 4         | Carol       | UK                 |
| 5         | David       | AUS                |
| 6         | Larry       | UK                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)

다음은 두 개 이상의 열(예:학생 국가 및 이름)에 대해 MySQL 정렬을 수행하는 쿼리입니다. -

mysql> select StudentId,StudentName,StudentCountryName from doubleSortDemo
   -> order by StudentCountryName,StudentName;

이것은 다음과 같은 출력을 생성합니다 -

+-----------+-------------+--------------------+
| StudentId | StudentName | StudentCountryName |
+-----------+-------------+--------------------+
| 5         | David       | AUS                |
| 1         | John        | AUS                |
| 4         | Carol       | UK                 |
| 6         | Larry       | UK                 |
| 2         | Sam         | UK                 |
| 3         | Bob         | US                 |
+-----------+-------------+--------------------+
6 rows in set (0.00 sec)