如何在 MySQL 中获取表的第一条和最后一条记录?
要获取第一条和最后一条记录,请使用 UNION。LIMIT 也用于获取所需的记录数。
让我们首先创建一个表 -
mysql> create table DemoTable694 ( EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeName varchar(100), EmployeeSalary int ); Query OK, 0 rows affected (0.58 sec)
使用插入命令向表中插入一些记录 -
mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Chris',457647); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Robert',90883); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('David',123532); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable694(EmployeeName,EmployeeSalary) values('Mike',989322); Query OK, 1 row affected (0.22 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable694;
这将产生以下输出 -
+------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeSalary | +------------+--------------+----------------+ | 1 | Chris | 457647 | | 2 | Robert | 90883 | | 3 | David | 123532 | | 4 | Mike | 989322 | +------------+--------------+----------------+ 4 rows in set (0.00 sec)
以下是获取第一条和最后一条记录的查询 -
mysql> (select *from DemoTable694 order by EmployeeId ASC LIMIT 1) UNION (select *from DemoTable694 order by EmployeeId DESC LIMIT 1);
这将产生以下输出 -
+------------+--------------+----------------+ | EmployeeId | EmployeeName | EmployeeSalary | +------------+--------------+----------------+ | 1 | Chris | 457647 | | 4 | Mike | 989322 | +------------+--------------+----------------+ 2 rows in set (0.00 sec)
广告