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

MySQL에서 문자열의 마지막 2자를 기준으로 ORDER BY 정렬하는 방법

MySQL에서는 ORDER BY와 함께 RIGHT() 함수를 사용하면 문자열의 마지막 2자를 기준으로 손쉽게 정렬할 수 있습니다. 이 방법은 고객 ID처럼 이름과 숫자가 결합된 문자열에서 숫자 부분만 추출해 정렬해야 할 때 특히 유용합니다.

기본 문법

SELECT yourColumnName FROM yourTableName ORDER BY RIGHT(yourColumnName, 2);

RIGHT(컬럼명, 2)는 해당 컬럼 값의 오른쪽 끝에서 2개의 문자를 반환하며, 이 값을 기준으로 정렬이 수행됩니다.

예제 테이블 생성

문법을 실제로 이해하기 위해 예제 테이블을 먼저 만들어 보겠습니다.

mysql> create table OrderByLast2CharactersDemo
    -> (
    -> CustomerId varchar(20),
    -> CustomerName varchar(20)
    -> );
Query OK, 0 rows affected (0.58 sec)

다음으로 INSERT 명령을 사용해 몇 개의 레코드를 삽입합니다.

mysql> insert into OrderByLast2CharactersDemo(CustomerId,CustomerName) values('John-98','John');
Query OK, 1 row affected (0.20 sec)
mysql> insert into OrderByLast2CharactersDemo(CustomerId,CustomerName) values('Carol-91','Carol');
Query OK, 1 row affected (0.21 sec)
mysql> insert into OrderByLast2CharactersDemo(CustomerId,CustomerName) values('Bob-99','Bob');
Query OK, 1 row affected (0.22 sec)
mysql> insert into OrderByLast2CharactersDemo(CustomerId,CustomerName) values('David-67','David');
Query OK, 1 row affected (0.15 sec)

SELECT 문으로 테이블의 모든 레코드를 확인해 보겠습니다.

mysql> select *from OrderByLast2CharactersDemo;

실행 결과는 다음과 같습니다.

+------------+--------------+
| CustomerId | CustomerName |
+------------+--------------+
| John-98    | John         |
| Carol-91   | Carol        |
| Bob-99     | Bob          |
| David-67   | David        |
+------------+--------------+
4 rows in set (0.00 sec)

이제 문자열의 마지막 2자를 기준으로 정렬하는 쿼리를 살펴보겠습니다.

Case 1: 오름차순(ASC) 정렬

오름차순으로 정렬하는 쿼리는 다음과 같습니다.

mysql> select CustomerId from OrderByLast2CharactersDemo ORDER BY RIGHT(CustomerId, 2);

실행 결과입니다.

+------------+
| CustomerId |
+------------+
| David-67   |
| Carol-91   |
| John-98    |
| Bob-99     |
+------------+
4 rows in set (0.01 sec)

마지막 두 자리 숫자인 67 → 91 → 98 → 99 순서로 정렬된 것을 확인할 수 있습니다.

Case 2: 내림차순(DESC) 정렬

내림차순으로 정렬하려면 쿼리 뒤에 DESC 키워드를 추가하면 됩니다.

mysql> select CustomerId from OrderByLast2CharactersDemo ORDER BY RIGHT(CustomerId, 2) DESC;

실행 결과입니다.

+------------+
| CustomerId |
+------------+
| Bob-99     |
| John-98    |
| Carol-91   |
| David-67   |
+------------+
4 rows in set (0.00 sec)

정리

RIGHT() 함수를 ORDER BY 절과 함께 사용하면 전체 문자열이 아닌 원하는 위치의 일부 문자만 기준으로 정렬할 수 있습니다. 오름차순이 기본값이며, 내림차순이 필요한 경우 DESC를 붙여주면 됩니다. 이 기법은 '이름-번호' 형태처럼 접미사에 숫자가 포함된 데이터를 관리할 때 매우 실용적으로 활용됩니다.