ラボ > MySQL:基本構文、日時関連

mySQLの日付が絡むWhere句

以前、以降、期間内の指定。betweenとか。

作成日:2018-04-19, 更新日:2019-05-17

基本

下記のようなテーブルがあったとき。

id price order_at
1 4500 2018-04-05
2 3200 2018-04-10
3 4900 2018-04-10
4 4600 2018-04-15
5 3500 2018-04-19

各クエリ

内容 where句
「4/10以前(4/10を含む)」の指定
where `order_at`<='2018-04-10'
「4/10未満(4/10を含まない)」の指定
where `order_at`<'2018-04-10'
「4/10以降(4/10を含む)」の指定
where '2018-04-10'<=`order_at`
「4/10超過(4/10を含まない)」の指定
where '2018-04-10'<`order_at`
「4/1~4/10(4/1、4/10を含む)」の指定1
where '2018-04-01'<=`order_at` and `order_at`<='2018-04-10'
「4/1~4/10(4/1、4/10を含む)」の指定2:between
where `order_at` between '2018-04-01' and '2018-04-10'

date型じゃなくdatetime型の場合のbetween

下記のようなテーブルがあったとき。

id price order_at
6 4500 2018-04-20 00:00:00
7 3200 2018-04-20 13:23:09
8 4900 2018-04-22 00:00:00
9 4600 2018-04-22 09:05:23

各クエリと結果

「4/20~4/22」でbetween(※「4/22」の「00:00:00」までが取得される)
`order_at` between '2018-04-20' and '2018-04-22'
id price order_at
6 4500 2018-04-20 00:00:00
7 3200 2018-04-20 13:23:09
8 4900 2018-04-22 00:00:00
4/22の終日まで欲しい(betweenじゃ無理かも)
betweenじゃないけど・・・

'2018-04-20'<=`order_at` and `order_at`<'2018-04-23'
id price order_at
6 4500 2018-04-20 00:00:00
7 3200 2018-04-20 13:23:09
8 4900 2018-04-22 00:00:00
9 4600 2018-04-22 09:05:23
▼別案:カラムの値を日付型に変換させる

'2018-04-20'<=DATE_FORMAT(`order_at`, '%Y-%m-%d') and DATE_FORMAT(`order_at`, '%Y-%m-%d') <='2018-04-22'

→これならbetweenにしても大丈夫そう。

めも

「4/20~4/22のデータ」が欲しいときの指定方法1
'2018-04-20'<=`order_at` and `order_at`<'2018-04-23'
「4/20~4/22のデータ」が欲しいときの指定方法2
'2018-04-20'<=`order_at` and `order_at`<('2018-04-22' + interval 1 day)

※プログラムが絡むとコッチのほうが何かと都合がいい。

「4/20~4/22のデータ」が欲しいときの指定方法3
'2018-04-20 00:00:00'<=`order_at` and `order_at`<'2018-04-23 00:00:00'

※datetime型を対象にするんだから、コレが正しいやりかただと思う。

「4/20~4/22のデータ」が欲しいときの指定方法4
'2018-04-20 00:00:00'<=`order_at` and `order_at`<='2018-04-22 23:59:59'

※ミリ秒が無いならコレでも良いと思う。

範囲が1日だけの場合

クエリを単純に発行するなら別に関係ないけど、プログラムが絡むと引数を減らしたい。

▼「4/20のデータ」が欲しいときの指定方法

'2018-04-20'<=`order_at` and `order_at`<('2018-04-20' + interval 1 day)

関連項目

Mysql unixtimeとdatetime型の相互変換