如何获取 MySQL 表中与最大 id 关联的数据?
mysqlmysqli database
我们首先按降序排序,然后获取与最大 id 关联的值 −
select *from yourTableName order by yourColumnName DESC LIMIT 1,1;
首先我们创建一个表 −
mysql> create table DemoTable -> ( -> Alldata int -> ); Query OK, 0 rows affected (0.63 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values(303); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values(560); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(100); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values(490); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values(498); Query OK, 1 row affected (0.14 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+---------+ | Alldata | +---------+ | 303 | | 560 | | 100 | | 490 | | 498 | +---------+ 5 rows in set (0.00 sec)
以下是获取与最大 id 关联的记录的查询 −
mysql> select *from DemoTable order by Alldata DESC LIMIT 1,1;
输出
+---------+ | Alldata | +---------+ | 498 | +---------+ 1 row in set (0.00 sec)