我很难创建一个高性能的数据库 Select . 以下 case :
A booking has 2 attributes departure
and arrival
.
Both attributes are type date
.
I want to select all Persons with bookings with departure: 1.month.ago
and no Booking in the future.
Relation:
class Booking
has_many :persons, class_name: 'Person', through: :stays
end
class Stay
belongs_to :booking, class_name: 'Booking'
belongs_to :person, class_name: 'Person'
end
class Person
has_many :bookings, class_name: 'Booking', through: :stays
end
因为数据库中有大约3.800.000个人,所以我不能在 Select 之后使用ruby逻辑进行 Select .
我试过一些请求,但我没有得到任何结果,即使有一些.
Person.joins(:bookings).where('bookings.departure < ? AND NOT EXISTS (SELECT 1 FROM bookings WHERE arrival >= ?)', 1.month.ago, Time.zone.today).find_each(&:clear)
是否可能有这样的数据库请求,或者我需要在活动记录中处理一个 case ,而其他 case 则通过逻辑处理?
Person.joins(:bookings).where('bookings.departure < ?', 1.month.ago).find_each do |pers|
pers.clear unless pers.bookings.where('arrival >= ?', Time.zone.today).exists?
end