如何从 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 - > ); Query OK, 0 rows affected (0.65 sec)
使用插入命令向表中插入一些记录。查询如下
mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Larry',date_add(now(),interval -1 month)); Query OK, 1 row affected (0.19 sec) mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Mike','2018-09-12 19:34:45'); Query OK, 1 row affected (0.43 sec) mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Sam','2017-11-24 14:30:40'); Query OK, 1 row affected (0.19 sec) mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('Carol','2019-02-12 11:30:41'); Query OK, 1 row affected (0.56 sec) mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('David',now()); Query OK, 1 row affected (0.22 sec) mysql> insert into MostRecentDateDemo(Name,ShippingDate) values('John','2018-12-31 12:59:58'); Query OK, 1 row affected (0.15 sec)
使用 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)
广告