다음은 구문입니다 -
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 -> ); Query OK, 0 rows affected (0.59 sec)
삽입 명령을 사용하여 테이블에 일부 레코드 삽입 -
mysql> insert into DemoTable1454 values('2019-10-01'); Query OK, 1 row affected (0.22 sec) mysql> insert into DemoTable1454 values('2019-10-03'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable1454 values('2019-10-05'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable1454 values('2019-10-04'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1454 values('2018-10-06'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1454 values('2019-10-06'); Query OK, 1 row affected (0.11 sec)
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)