Computer >> 컴퓨터 >  >> 프로그래밍 >> MySQL

MySQL에서 여러 열을 동시에 정렬하는 방법 – ORDER BY 절 완벽 가이드

MySQL에서 두 개 이상의 열을 동시에 정렬하기

MySQL에서 한 번에 두 개 이상의 열을 기준으로 데이터를 정렬하려면 ORDER BY 절을 사용하면 됩니다. ORDER BY 뒤에 정렬 기준이 될 열 이름을 쉼표(,)로 구분하여 나열하면, 첫 번째 열을 우선으로 정렬한 뒤 그 값이 서로 같은 행들에 대해서만 두 번째 열을 기준으로 추가 정렬이 수행됩니다.

기본 문법은 다음과 같습니다.

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

1단계: 예제 테이블 생성

먼저 실습에 사용할 테이블을 만들어 보겠습니다.

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)

2단계: 데이터 삽입

INSERT 명령을 사용하여 학생 데이터를 테이블에 입력합니다.

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)

3단계: 전체 데이터 조회

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)

4단계: 두 개의 열로 정렬 실행

이제 국가명(StudentCountryName)을 1차 기준으로, 이름(StudentName)을 2차 기준으로 정렬하는 쿼리를 실행해 보겠습니다.

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)

결과 분석

출력 결과를 살펴보면, 먼저 국가명이 AUS → UK → US 순서(알파벳 오름차순)로 정렬되었고, 같은 국가 내에서는 이름의 알파벳 순서대로 정렬된 것을 확인할 수 있습니다. 즉, AUS 그룹에서는 David가 John보다 앞에 위치하고, UK 그룹에서는 Carol → Larry → Sam 순으로 배치되었습니다.

추가 팁: 열별 정렬 방향 지정하기

각 열마다 정렬 방향을 개별적으로 지정할 수도 있습니다. 오름차순은 ASC(기본값), 내림차순은 DESC 키워드를 사용합니다. 예를 들어 국가명은 오름차순으로, 이름은 내림차순으로 정렬하고 싶다면 다음과 같이 작성합니다.

order by StudentCountryName ASC, StudentName DESC;

이처럼 ORDER BY 절에 여러 열을 조합하면 복잡한 요구 사항의 정렬도 손쉽게 처리할 수 있으며, 보고서나 목록 화면을 구성할 때 매우 유용하게 활용됩니다.