獲取 MySQL 表中的最新條目?


您可以使用 ORDER BY 獲取 MySQL 表中的最新條目。第一種方法如下

案例 1:使用 DESC LIMIT

SELECT * FROM yourTableName ORDER BY yourColumnName DESC LIMIT 1;

第二種方法如下

案例 2:使用 MAX()

SET @anyVariableName = (SELECT MAX(yourColumnName) FROM yourTableName);
SELECT *FROM yourtableName WHERE yourColumnName = @anyVariableName;

現在為了理解以上兩種方法,讓我們建立一個表。建立表的查詢如下

mysql> create table lastEntryDemo
   -> (
   -> Id int NOt NULL AUTO_INCREMENT,
   -> Name varchar(30),
   -> Age int,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (0.71 sec)

使用插入命令在表中插入一些記錄。查詢如下

mysql> insert into lastEntryDemo(Name,Age) values('Larry',24);
Query OK, 1 row affected (0.14 sec)

mysql> insert into lastEntryDemo(Name,Age) values('John',21);
Query OK, 1 row affected (0.19 sec)

mysql> insert into lastEntryDemo(Name,Age) values('David',22);
Query OK, 1 row affected (0.18 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Bob',25);
Query OK, 1 row affected (0.20 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Carol',29);
Query OK, 1 row affected (0.17 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Mike',23);
Query OK, 1 row affected (0.14 sec)

mysql> insert into lastEntryDemo(Name,Age) values('Sam',20);
Query OK, 1 row affected (0.15 sec)

使用 select 語句顯示錶中的所有記錄。查詢如下

mysql> select *from lastEntryDemo;

以下是輸出

+----+-------+------+
| Id | Name  | Age  |
+----+-------+------+
|  1 | Larry |   24 |
|  2 | John  |   21 |
|  3 | David |   22 |
|  4 | Bob   |   25 |
|  5 | Carol |   29 |
|  6 | Mike  |   23 |
|  7 | Sam   |   20 |
+----+-------+------+
7 rows in set (0.00 sec)

以下是使用 ORDER BY 獲取最新條目的查詢。

案例 1:DESC LIMIT

查詢如下

mysql> select *from lastEntryDemo order by Name desc limit 1;

以下是輸出

+----+------+------+
| Id | Name | Age  |
+----+------+------+
| 7  | Sam  | 20   |
+----+------+------+
1 row in set (0.00 sec)

案例 2:使用 MAX()

查詢如下

mysql> set @MaxId = (select max(Id) from lastEntryDemo);
Query OK, 0 rows affected (0.00 sec)

mysql> select *from lastEntryDemo where Id = @MaxId;

以下是輸出

+----+------+------+
| Id | Name | Age  |
+----+------+------+
| 7  | Sam  | 20   |
+----+------+------+
1 row in set (0.00 sec)

更新於: 2019 年 7 月 30 日

1K+ 瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始
廣告