MySQLでn日後・n日前の時間を取得する方法
結論
mysql> select now() + INTERVAL 1 DAY;
+------------------------+
| now() + INTERVAL 1 DAY |
+------------------------+
| 2020-07-08 16:13:32 |
+------------------------+
1 row in set (0.00 sec)
mysql> select now() - INTERVAL 1 DAY;
+------------------------+
| now() - INTERVAL 1 DAY |
+------------------------+
| 2020-07-06 16:14:51 |
+------------------------+
1 row in set (0.00 sec)
INTERVAL構文でできます。簡単ですね。
ちなみにDAYだけではなく、下記のunit(単位)であれば指定可能らしいです。
unit 値 | 要求される expr 書式 |
---|---|
MICROSECOND | MICROSECONDS |
SECOND | SECONDS |
MINUTE | MINUTES |
HOUR | HOURS |
DAY | DAYS |
WEEK | WEEKS |
MONTH | MONTHS |
QUARTER | QUARTERS |
YEAR | YEARS |
SECOND_MICROSECOND | 'SECONDS.MICROSECONDS' |
MINUTE_MICROSECOND | 'MINUTES:SECONDS.MICROSECONDS' |
MINUTE_SECOND | 'MINUTES:SECONDS' |
HOUR_MICROSECOND | 'HOURS:MINUTES:SECONDS.MICROSECONDS' |
HOUR_SECOND | 'HOURS:MINUTES:SECONDS' |
HOUR_MINUTE | 'HOURS:MINUTES' |
DAY_MICROSECOND | 'DAYS HOURS:MINUTES:SECONDS.MICROSECONDS' |
DAY_SECOND | 'DAYS HOURS:MINUTES:SECONDS' |
DAY_MINUTE | 'DAYS HOURS:MINUTES' |
DAY_HOUR | 'DAYS HOURS' |
YEAR_MONTH | 'YEARS-MONTHS' |
バージョン
$ mysql --version
mysql Ver 14.14 Distrib 5.7.30, for Linux (x86_64) using EditLine wrapper