如何从MySQL中几个可能的时间戳中选择最近的日期?
您可以借助ORDER BY子句从一组可能的时间戳中选择最新的日期。
语法如下
SELECT yourColumnName1,yourColumnName2,...N FROM yourTableName ORDER BY yourTimestampColumnName DESC LIMIT 1;
为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table MostRecentDateDemo- > (
- > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
- > Name varchar(10),
- > ShippingDate timestamp
- > );
使用insert命令在表中插入一些记录。查询如下
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Larry',date_add(now(),interval -1 month));mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Mike','2018-09-12 19:34:45');
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Sam','2017-11-24 14:30:40');
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Carol','2019-02-12 11:30:41');
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('David',now());
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('John','2018-12-31 12:59:58');
使用select语句显示表中的所有记录。
查询如下
mysql> select *from MostRecentDateDemo;
以下是输出
+----+-------+---------------------+| Id | Name | ShippingDate |
+----+-------+---------------------+
| 1 | Larry | 2019-01-14 17:17:08 |
| 2 | Mike | 2018-09-12 19:34:45 |
| 3 | Sam | 2017-11-24 14:30:40 |
| 4 | Carol | 2019-02-12 11:30:41 |
| 5 | David | 2019-02-14 17:19:34 |
| 6 | John | 2018-12-31 12:59:58 |
+----+-------+---------------------+
6 rows in set (0.00 sec)
这是选择最近日期的查询
mysql> select Id,Name,ShippingDate from MostRecentDateDemo order by ShippingDate desc limit 1;
以下是输出
+----+-------+---------------------+| Id | Name | ShippingDate |
+----+-------+---------------------+
| 5 | David | 2019-02-14 17:19:34 |
+----+-------+---------------------+
1 row in set (0.00 sec)
以上是 如何从MySQL中几个可能的时间戳中选择最近的日期? 的全部内容, 来源链接: utcz.com/z/331031.html