PgSQL 日期查询记录
昨天有个需求给我整懵了,DB里有:
# days :integer, comment: '有效期'
# actived_at :datetime, comment: '激活日期'
但是激活日期可能为空,在激活的时候没有记录过期日期,是通过计算的,然后我 SQL 有点菜,搞了大半天才搞出来,所以记录一下,需求:
- 三天内到期
- 今日到期
其实很简单了,只不过是我太菜了...,逻辑上就是:
三天内到期:激活日期(actived_at) + 有效期(days)在 Date.today..3.days.after的范围内,so,Ruby代码:
# actived_at is not null 是去除未激活的
scope :three_days_expired, -> { where('actived_at is not null and Date(actived_at) + days between ? and ?', Date.today, 3.days.after) }
今日到期:激活日期(actived_at) + 有效期(days)= Date.today,代码:
# actived_at is not null 同上
scope :due_today, -> { where('actived_at is not null and Date(actived_at) + days = ?', Date.today) }