97
88

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

MySQLで「おととい」「昨日」「明日」「あさって」

Last updated at Posted at 2013-04-03

概要

MySQLにて、SQLで期間データを取得する際によく利用するSQLを記載しています。

SQL

SELECT DATE_FORMAT(DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH), '%Y-%m-01');  -- 前月の月初
SELECT LAST_DAY(DATE_SUB(CURRENT_DATE, INTERVAL 1 MONTH)); -- 前月の月末

SELECT DATE_FORMAT(CURRENT_DATE, '%Y-%m-01'); -- 当月の月初

SELECT DATE_SUB(CURRENT_DATE, INTERVAL 2 DAY); -- おととい
SELECT DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY); -- 昨日

SELECT CURRENT_DATE; -- 現在

SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY); -- 明日
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 2 DAY); -- あさって

SELECT LAST_DAY(CURRENT_DATE); -- 当月の月末

SELECT DATE_FORMAT(DATE_ADD(CURRENT_DATE, INTERVAL 1 MONTH), '%Y-%m-01');  -- 次月の月初
SELECT LAST_DAY(DATE_ADD(CURRENT_DATE, INTERVAL 1 MONTH)); -- 次月の月末

補足

現在の日付について

CURRENT_DATE() および CURRENT_DATEは、CURDATE()のエイリアス。

日付の演算について

下記はどちらも結果が同じ。

DATE_SUB(CURRENT_DATE, INTERVAL 1 DAY)
DATE_ADD(CURRENT_DATE, INTERVAL - 1 DAY)

留意点

DATETIME型項目を条件に当月データを修正したりする場合は、下記に注意。

よくある誤り

SELECT
  *
FROM
  some_of_table
WHERE
  -- 月末の値が正しく取れない
  created_at BETWEEN DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') AND LAST_DAY(CURRENT_DATE)
;

正しい

SELECT
  *
FROM
  some_of_table
WHERE
  created_at >= DATE_FORMAT(CURRENT_DATE, '%Y-%m-01')
AND
  created_at < DATE_ADD(LAST_DAY(CURRENT_DATE), INTERVAL 1 DAY)
;

もしくは

SELECT
  *
FROM
  some_of_table
WHERE
  created_at BETWEEN DATE_FORMAT(CURRENT_DATE, '%Y-%m-01') AND DATE_FORMAT(LAST_DAY(CURRENT_DATE), '%Y-%m-%d 23:59:59')
;

参考

MySQL :: MySQL 5.7 Reference Manual :: 12.6 Date and Time Functions
MySQL :: MySQL 8.0 Reference Manual :: 12.6 Date and Time Functions

97
88
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
97
88

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?