如何獲取與 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)
廣告