ActiveRecord 查询 (PostgreSQL) 中的日期时间算法 [英] DateTime arithmetic in an ActiveRecord query (PostgreSQL)
问题描述
我在 User
/users
表中有两个 datetime
列:created_at
和 birthdate代码>.我想查找出生日期在其创建日期之前不到 13 年的用户.
I have two datetime
columns in a User
/users
table: created_at
and birthdate
. I'd like to find users whose birthdate is less than 13 years before their creation date.
等效的 Rails if
语句将是 ((created_at -birthdate) <13.years)
The equivalent Rails if
statement would be ((created_at - birthdate) < 13.years)
如何将其转换为 ActiveRecord 查询(可在 PostgreSQL 上使用的查询)?这甚至可能吗,还是我必须手动遍历所有记录?
How do I translate this to an ActiveRecord query (one that'll work on PostgreSQL)? Is this even possible, or will I have to iterate over all records manually?
推荐答案
最简单的方法是使用 间隔,那么它几乎是 Rails 版本的直接音译:
The easiest way to do this is to use an interval, then it is pretty much a straight transliteration of the Rails version:
User.where(%q{created_at - birthdate < interval '13 years'})
两个时间戳(或时间戳和日期)之间的差异是一个间隔,因此您只需要比较右侧的适当值即可.
The difference between two timestamps (or a timestamp and a date) is an interval so you just need the appropriate value on the right side of your comparison.
这篇关于ActiveRecord 查询 (PostgreSQL) 中的日期时间算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!