Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What is going on with this article?
@kiyo_e

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

More than 5 years have passed since last update.

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
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
kiyo_e
sowxp
体験の総合商社。体験ギフトの販売や、体験の予約サイトの開発・運営をしています。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
3
Help us understand the problem. What is going on with this article?