MySQL에서 마지막 20개 레코드를 오름차순으로 조회하기
테이블에 저장된 데이터 중 마지막 20개의 레코드를 오름차순(ASC)으로 정렬하여 가져오려면 서브쿼리와 LIMIT 절을 함께 활용하면 됩니다. 핵심 아이디어는 간단합니다. 먼저 내부 쿼리에서 기준 컬럼을 내림차순(DESC)으로 정렬한 뒤 20개의 행만 추출하고, 그 결과를 외부 쿼리에서 다시 오름차순으로 정렬하는 방식입니다.
기본 문법
SELECT *FROM
(
SELECT *FROM yourTableName ORDER BY yourColumnName desc limit 20
)
anyVariableName order by anyVariableName.yourColumnName;위 문법을 실제로 이해하기 위해 예제 테이블을 하나 만들어 보겠습니다.
1. 예제 테이블 생성
상품 정보를 저장할 테이블을 생성하는 쿼리는 다음과 같습니다.
mysql> create table ProductInformation
-> (
-> ProductId int,
-> ProductName varchar(100),
-> ProductPrice int
-> );
Query OK, 0 rows affected (0.50 sec)2. 샘플 데이터 삽입
INSERT 명령어를 사용해 총 23개의 상품 레코드를 입력합니다.
mysql> insert into ProductInformation values(101,'Product-1',200); Query OK, 1 row affected (0.16 sec) mysql> insert into ProductInformation values(102,'Product-2',300); Query OK, 1 row affected (0.23 sec) mysql> insert into ProductInformation values(103,'Product-3',700); Query OK, 1 row affected (0.09 sec) mysql> insert into ProductInformation values(104,'Product-4',100); Query OK, 1 row affected (0.15 sec) mysql> insert into ProductInformation values(105,'Product-5',1500); Query OK, 1 row affected (0.18 sec) mysql> insert into ProductInformation values(106,'Product-6',1200); Query OK, 1 row affected (0.18 sec) mysql> insert into ProductInformation values(107,'Product-7',1300); Query OK, 1 row affected (0.17 sec) mysql> insert into ProductInformation values(108,'Product-8',1600); Query OK, 1 row affected (0.29 sec) mysql> insert into ProductInformation values(109,'Product-9',1250); Query OK, 1 row affected (0.15 sec) mysql> insert into ProductInformation values(110,'Product-10',1900); Query OK, 1 row affected (0.15 sec) mysql> insert into ProductInformation values(111,'Product-11',1870); Query OK, 1 row affected (0.13 sec) mysql> insert into ProductInformation values(112,'Product-12',1876); Query OK, 1 row affected (0.11 sec) mysql> insert into ProductInformation values(113,'Product-13',1869); Query OK, 1 row affected (0.19 sec) mysql> insert into ProductInformation values(114,'Product-14',1456); Query OK, 1 row affected (0.25 sec) mysql> insert into ProductInformation values(115,'Product-15',1860); Query OK, 1 row affected (0.16 sec) mysql> insert into ProductInformation values(116,'Product-16',359); Query OK, 1 row affected (0.21 sec) mysql> insert into ProductInformation values(117,'Product-17',1667); Query OK, 1 row affected (0.09 sec) mysql> insert into ProductInformation values(118,'Product-18',1467); Query OK, 1 row affected (0.11 sec) mysql> insert into ProductInformation values(119,'Product-19',2134); Query OK, 1 row affected (0.24 sec) mysql> insert into ProductInformation values(120,'Product-20',3450); Query OK, 1 row affected (0.10 sec) mysql> insert into ProductInformation values(121,'Product-21',198); Query OK, 1 row affected (0.22 sec) mysql> insert into ProductInformation values(122,'Product-22',195); Query OK, 1 row affected (0.21 sec) mysql> insert into ProductInformation values(123,'Product-23',10000); Query OK, 1 row affected (0.15 sec)
3. 전체 데이터 확인
SELECT 문으로 테이블에 저장된 모든 레코드를 조회해 보겠습니다.
mysql> select *from ProductInformation;
실행 결과는 다음과 같으며, 총 23개의 레코드가 저장되어 있는 것을 확인할 수 있습니다.
+-----------+-------------+--------------+ | ProductId | ProductName | ProductPrice | +-----------+-------------+--------------+ | 101 | Product-1 | 200 | | 102 | Product-2 | 300 | | 103 | Product-3 | 700 | | 104 | Product-4 | 100 | | 105 | Product-5 | 1500 | | 106 | Product-6 | 1200 | | 107 | Product-7 | 1300 | | 108 | Product-8 | 1600 | | 109 | Product-9 | 1250 | | 110 | Product-10 | 1900 | | 111 | Product-11 | 1870 | | 112 | Product-12 | 1876 | | 113 | Product-13 | 1869 | | 114 | Product-14 | 1456 | | 115 | Product-15 | 1860 | | 116 | Product-16 | 359 | | 117 | Product-17 | 1667 | | 118 | Product-18 | 1467 | | 119 | Product-19 | 2134 | | 120 | Product-20 | 3450 | | 121 | Product-21 | 198 | | 122 | Product-22 | 195 | | 123 | Product-23 | 10000 | +-----------+-------------+--------------+ 23 rows in set (0.00 sec)
4. 마지막 20개 레코드를 오름차순으로 조회
이제 테이블에서 마지막 20개의 레코드를 오름차순으로 가져오는 쿼리를 실행해 보겠습니다. 내부 서브쿼리에서 ProductId를 기준으로 내림차순 정렬 후 20개를 제한하고, 외부 쿼리에서 다시 오름차순으로 정렬합니다.
mysql> select *from
-> (
-> select *from ProductInformation order by ProductId desc limit 20
-> ) t1 order by t1.ProductId asc;실행 결과는 다음과 같습니다. ProductId 104부터 123까지, 즉 가장 최근에 입력된 20개의 레코드가 오름차순으로 출력됩니다.
+-----------+-------------+--------------+ | ProductId | ProductName | ProductPrice | +-----------+-------------+--------------+ | 104 | Product-4 | 100 | | 105 | Product-5 | 1500 | | 106 | Product-6 | 1200 | | 107 | Product-7 | 1300 | | 108 | Product-8 | 1600 | | 109 | Product-9 | 1250 | | 110 | Product-10 | 1900 | | 111 | Product-11 | 1870 | | 112 | Product-12 | 1876 | | 113 | Product-13 | 1869 | | 114 | Product-14 | 1456 | | 115 | Product-15 | 1860 | | 116 | Product-16 | 359 | | 117 | Product-17 | 1667 | | 118 | Product-18 | 1467 | | 119 | Product-19 | 2134 | | 120 | Product-20 | 3450 | | 121 | Product-21 | 198 | | 122 | Product-22 | 195 | | 123 | Product-23 | 10000 | +-----------+-------------+--------------+ 20 rows in set (0.00 sec)
5. 내림차순으로 조회하기
만약 결과를 내림차순(DESC)으로 정렬하고 싶다면, 외부 쿼리의 ORDER BY 절에 desc 키워드를 사용하면 됩니다.
mysql> select *from -> ( -> select *from ProductInformation order by ProductId desc limit 20 -> ) t2 order by t2.ProductId desc;
실행 결과는 다음과 같습니다. 같은 20개의 레코드가 큰 값부터 작은 값 순으로 출력되는 것을 확인할 수 있습니다.
+-----------+-------------+--------------+ | ProductId | ProductName | ProductPrice | +-----------+-------------+--------------+ | 123 | Product-23 | 10000 | | 122 | Product-22 | 195 | | 121 | Product-21 | 198 | | 120 | Product-20 | 3450 | | 119 | Product-19 | 2134 | | 118 | Product-18 | 1467 | | 117 | Product-17 | 1667 | | 116 | Product-16 | 359 | | 115 | Product-15 | 1860 | | 114 | Product-14 | 1456 | | 113 | Product-13 | 1869 | | 112 | Product-12 | 1876 | | 111 | Product-11 | 1870 | | 110 | Product-10 | 1900 | | 109 | Product-9 | 1250 | | 108 | Product-8 | 1600 | | 107 | Product-7 | 1300 | | 106 | Product-6 | 1200 | | 105 | Product-5 | 1500 | | 104 | Product-4 | 100 | +-----------+-------------+--------------+ 20 rows in set (0.00 sec)
정리
MySQL에서 마지막 N개의 레코드를 원하는 정렬 순서로 조회하려면 다음 두 단계를 기억하면 됩니다.
1단계: 서브쿼리에서 기준 컬럼을 내림차순(DESC)으로 정렬하고 LIMIT으로 원하는 개수만큼 제한합니다.
2단계: 외부 쿼리에서 해당 결과를 오름차순(ASC) 또는 내림차순(DESC)으로 다시 정렬합니다.
이 패턴은 게시판의 최신 글 목록, 로그 데이터의 최근 기록 조회 등 실무에서 매우 자주 활용되므로 꼭 익혀두시기 바랍니다.