MySQL 如何选择最后一行
要选择最后一行,我们可以使用带有desc(降序)属性和Limit 1的ORDER BY子句。让我们首先创建一张表,并使用insert命令插入一些记录。
查询如下:
mysql> create table getLastRecord
-> (
-> Id int,
-> Name varchar(100)
-> );
Query OK, 0 rows affected (0.61 sec)
创建上述表之后,我们将使用insert命令插入记录。
mysql> insert into getLastRecord values(1,'John');
Query OK, 1 row affected (0.13 sec)
mysql> insert into getLastRecord values(2,'Ramit');
Query OK, 1 row affected (0.22 sec)
mysql> insert into getLastRecord values(3,'Johnson');
Query OK, 1 row affected (0.13 sec)
mysql> insert into getLastRecord values(4,'Carol');
Query OK, 1 row affected (0.79 sec)
使用select语句显示所有记录。
mysql> select *from getLastRecord;
输出如下。
+------+---------+
| Id | Name |
+------+---------+
| 1 | John |
| 2 | Ramit |
| 3 | Johnson |
| 4 | Carol |
+------+---------+
4 rows in set (0.00 sec)
我们的最后一个记录的id是4,名称为“Carol”。要获取最后一条记录,可以使用以下查询语句。
mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1;
输出如下。
+------+-------+
| Id | Name |
+------+-------+
| 4 | Carol |
+------+-------+
1 row in set (0.00 sec)
以上输出显示,我们已获取了最后一条记录,ID为4,名称为Carol。
阅读更多:MySQL 教程