3
3

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 5 years have passed since last update.

MySQLのDateTime型のカラムに、Date型のクエリを投げる時は注意

Posted at

DateTime型にDate型のクエリを投げると、自動補完してくれる

datetime型にdate型のクエリを投げると、こんな感じのSQLを吐く

User.where(created_at: (Date.today)..(90.days.since.to_date)).to_sql
=> "SELECT `users`.* FROM `users`  WHERE (`users`.`created_at` BETWEEN '2015-07-16' AND '2015-10-14')"

MySQL側では、以下のように 00:00:00をつけた形で処理してくれる。

BETWEEN '2015-07-16 00:00:00' AND '2015-10-14 00:00:00'

localtimeを使うと微妙にずれる

RailsではDBにすべてUTCで保存し、LocalTimeで処理するときは、内部的に復元して使うため、結果が微妙にずれる。

下記例では、いずれもTimeWithZoneに変換して実行

User.where(created_at: (Date.current.beginning_of_day)..(90.days.since.beginning_of_day)).to_sql
=> "SELECT `users`.* FROM `users`  WHERE (`users`.`created_at` BETWEEN '2015-07-15 15:00:00' AND '2015-10-13 15:00:00')"

型に合わせよう

とりあえず型に合わせるように、きちんと変換しておくか、すべてUTC前提で動いて行くと、困ったことにはならなそう。
UTC前提は結構大変なので、実際には変換しておくほうが現実的?

参考

3
3
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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?