하위 쿼리를 사용할 수 있습니다. 다음은 구문입니다 -
SELECT * FROM ( SELECT * FROM yourTableName ORDER BY yourIdColumnName DESC LIMIT 3 ) anyAliasName ORDER BY yourIdColumnName;
먼저 테이블을 생성하겠습니다 -
mysql> create table DemoTable ( ClientId int NOT NULL AUTO_INCREMENT PRIMARY KEY, ClientName varchar(100) ); Query OK, 0 rows affected (0.60 sec)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
mysql> insert into DemoTable(ClientName) values('Larry'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable(ClientName) values('Chris'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ClientName) values('Bob'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(ClientName) values('David'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(ClientName) values('Carol'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(ClientName) values('Robert'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(ClientName) values('Sam'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(ClientName) values('Mike'); Query OK, 1 row affected (0.12 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select *from DemoTable;
이것은 다음과 같은 출력을 생성합니다 -
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 1 | Larry | | 2 | Chris | | 3 | Bob | | 4 | David | | 5 | Carol | | 6 | Robert | | 7 | Sam | | 8 | Mike | +----------+------------+ 8 rows in set (0.00 sec)
다음은 id ASC −
로 데이터베이스 순서에서 마지막 3개 행을 선택하는 쿼리입니다.mysql> SELECT * FROM ( SELECT * FROM DemoTable ORDER BY ClientId DESC LIMIT 3 ) tbl ORDER BY ClientId ASC;
이것은 다음과 같은 출력을 생성합니다 -
+----------+------------+ | ClientId | ClientName | +----------+------------+ | 6 | Robert | | 7 | Sam | | 8 | Mike | +----------+------------+ 3 rows in set (0.00 sec)