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

MySQL에서 테이블의 뒤에서 두 번째 행 조회하는 방법 (ORDER BY + LIMIT)

MySQL에서 테이블의 뒤에서 두 번째(마지막에서 두 번째) 행을 가져오려면 ORDER BY 절과 LIMIT 절을 함께 사용해야 합니다.

기본 문법

select * from yourTableName order by yourColumnName DESC LIMIT 1,1;

여기서 ORDER BY ... DESC는 지정한 컬럼을 기준으로 내림차순 정렬을 수행하고, LIMIT 1,1은 정렬된 결과 중 첫 번째 행은 건너뛰고(offset=1) 그 다음 한 개의 행(개수=1)만 반환하라는 의미입니다. 즉, 내림차순 기준으로 두 번째에 해당하는 행, 바로 '마지막에서 두 번째 행'이 조회됩니다.

예제 테이블 생성

문법을 실제로 이해하기 위해 예제 테이블을 만들어 보겠습니다. 아래 쿼리로 테이블을 생성합니다.

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

샘플 데이터 삽입

INSERT 명령을 사용하여 테이블에 여러 개의 레코드를 삽입합니다.

mysql> insert into secondLastDemo(StudentName) values('Larry');
Query OK, 1 row affected (0.15 sec)
mysql> insert into secondLastDemo(StudentName) values('Carol');
Query OK, 1 row affected (0.09 sec)
mysql> insert into secondLastDemo(StudentName) values('Bob');
Query OK, 1 row affected (0.10 sec)
mysql> insert into secondLastDemo(StudentName) values('Sam');
Query OK, 1 row affected (0.09 sec)
mysql> insert into secondLastDemo(StudentName) values('Mike');
Query OK, 1 row affected (0.10 sec)
mysql> insert into secondLastDemo(StudentName) values('David');
Query OK, 1 row affected (0.08 sec)
mysql> insert into secondLastDemo(StudentName) values('Maxwell');
Query OK, 1 row affected (0.10 sec)
mysql> insert into secondLastDemo(StudentName) values('Robert');
Query OK, 1 row affected (0.13 sec)
mysql> insert into secondLastDemo(StudentName) values('James');
Query OK, 1 row affected (0.14 sec)
mysql> insert into secondLastDemo(StudentName) values('Chris');
Query OK, 1 row affected (0.11 sec)
mysql> insert into secondLastDemo(StudentName) values('Ramit');
Query OK, 1 row affected (0.08 sec)

전체 데이터 확인

SELECT 문을 사용하여 테이블의 모든 레코드를 조회합니다.

mysql> select *from secondLastDemo;

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

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | Larry       |
| 2         | Carol       |
| 3         | Bob         |
| 4         | Sam         |
| 5         | Mike        |
| 6         | David       |
| 7         | Maxwell     |
| 8         | Robert      |
| 9         | James       |
| 10        | Chris       |
| 11        | Ramit       |
+-----------+-------------+
11 rows in set (0.00 sec)

마지막에서 두 번째 행 조회하기

이제 MySQL에서 테이블의 마지막에서 두 번째 행을 가져오는 쿼리를 실행해 보겠습니다.

mysql> select *from secondLastDemo order by StudentId DESC LIMIT 1,1;

StudentId를 기준으로 내림차순 정렬하면 가장 큰 값인 11(Ramit)이 첫 번째가 되고, LIMIT 1,1에 의해 이를 건너뛴 다음 행인 StudentId 10이 반환됩니다. 결과는 다음과 같습니다.

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 10        | Chris       |
+-----------+-------------+
1 row in set (0.00 sec)

위 출력에서 볼 수 있듯이, 전체 11개 레코드 중 마지막 레코드인 'Ramit'을 제외한 뒤에서 두 번째 레코드인 'Chris'(StudentId: 10)가 성공적으로 조회되었습니다.

정리

ORDER BY 컬럼명 DESC LIMIT 1,1 패턴은 특정 컬럼 기준으로 N번째 최근 값을 구할 때 유용하게 활용할 수 있습니다. 예를 들어 LIMIT 2,1로 변경하면 세 번째 최근 행을, offset 숫자를 조절하면 원하는 순번의 행을 손쉽게 가져올 수 있습니다.