以下是语法-
select * from yourTableName order by ( yourColumnName> now()) desc, (case when yourColumnName > now() then yourColumnName end) , yourColumnName desc limit 1;
让我们首先创建一个表-
mysql> create table DemoTable1454 -> ( -> ShippingDate date -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1454 values('2019-10-01'); mysql> insert into DemoTable1454 values('2019-10-03'); mysql> insert into DemoTable1454 values('2019-10-05'); mysql> insert into DemoTable1454 values('2019-10-04'); mysql> insert into DemoTable1454 values('2018-10-06'); mysql> insert into DemoTable1454 values('2019-10-06');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1454;
这将产生以下输出-
+--------------+ | ShippingDate | +--------------+ | 2019-10-01 | | 2019-10-03 | | 2019-10-05 | | 2019-10-04 | | 2018-10-06 | | 2019-10-06 | +--------------+ 6 rows in set (0.00 sec)
当前日期如下-
mysql> select now(); +---------------------+ | now() | +---------------------+ | 2019-10-04 21:30:01 | +---------------------+ 1 row in set (0.00 sec)
这是获取两天之间的下一个最近的一天的查询-
mysql> select * from DemoTable1454 -> order by ( ShippingDate > now()) desc, -> (case when ShippingDate > now() then ShippingDate end) , -> ShippingDate desc -> limit 1;
这将产生以下输出-
+--------------+ | ShippingDate | +--------------+ | 2019-10-05 | +--------------+ 1 row in set (0.00 sec)