如何从MySQL结果中选择第一个和最后一个数据行?

您可以使用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
   -> );

示例

使用insert命令在表中插入一些记录。查询如下-

mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('John',23);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Bob',13);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Larry',24);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Sam',14);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Mike',31);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('James',18);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge)
values('Maxwell',28);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('David',27);
mysql> insert into FirstAndLastDataDemo(EmployeeName,EmployeeAge) values('Chris',22);

使用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)