MIN() 및 MAX()를 사용하여 첫 번째 및 마지막 데이터 행을 선택할 수 있습니다. 구문은 다음과 같습니다 -
SELECT * FROM yourTableName WHERE yourColumnName = (SELECT MIN(yourColumnName) FROM yourTableName) UNION SELECT * FROM yourTableName WHERE yourColumnName = (SELECT MAX(yourColumnName) FROM yourTableName) ;
위의 구문을 이해하기 위해 테이블을 생성해 보겠습니다. 테이블을 생성하는 쿼리는 다음과 같습니다 -
mysql> create table FirstAndLastDataDemo -> ( -> EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> EmployeeName varchar(20), -> EmployeeAge int -> ); Query OK, 0 rows affected (0.59 sec)
예
삽입 명령을 사용하여 테이블에 일부 레코드를 삽입하십시오. 쿼리는 다음과 같습니다 -
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23); Query OK, 1 row affected (0.15 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13); Query OK, 1 row affected (0.11 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24); Query OK, 1 row affected (0.14 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14); Query OK, 1 row affected (0.18 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31); Query OK, 1 row affected (0.10 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('James',18); Query OK, 1 row affected (0.16 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Maxwell',28); Query OK, 1 row affected (0.17 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27); Query OK, 1 row affected (0.12 sec) mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22); Query OK, 1 row affected (0.19 sec)
select 문을 사용하여 테이블의 모든 레코드 표시 -
mysql> select *from FirstAndLastDataDemo;
출력
+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | John | 23 | | 2 | Bob | 13 | | 3 | Larry | 24 | | 4 | Sam | 14 | | 5 | Mike | 31 | | 6 | James | 18 | | 7 | Maxwell | 28 | | 8 | David | 27 | | 9 | Chris | 22 | +------------+--------------+-------------+ 9 rows in set (0.00 sec)
다음은 첫 번째 행 데이터와 마지막 행 데이터를 가져오는 쿼리입니다. -
mysql> SELECT * -> FROM FirstAndLastDataDemo -> WHERE EmployeeId = (SELECT MIN(EmployeeId) FROM FirstAndLastDataDemo) -> UNION -> SELECT * -> FROM FirstAndLastDataDemo -> WHERE EmployeeId = (SELECT MAX(EmployeeId) FROM FirstAndLastDataDemo);
출력
+------------+--------------+-------------+ | EmployeeId | EmployeeName | EmployeeAge | +------------+--------------+-------------+ | 1 | John | 23 | | 9 | Chris | 22 | +------------+--------------+-------------+ 2 rows in set (0.00 sec)