如何获取与 MySQL 表中最大 ID 关联的数据?
我们将首先按 DESC 排序,然后获取与最大 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)
使用插入命令将一些记录插入表格 -
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)
广告