使用 Rails 改进查询的 SQL 案例语句
发布时间:2022-07-17 05:45:32 227
相关标签: # 数据库
目前,我有一些代码可以从我们所有的预订中提取所有过去的旅行。然而,为了计算旅行结束日期,我必须使用其他字段。
这个Booking
使用Rails初始化ApplicationRecord
:
class Booking < ApplicationRecord
# `start_date` is an `ActiveSupport::TimeWithZone instance
# `trip_length` is a string that's stored in the db
# and that starts with the length of the trip ("1_day", "2_day", etc).
def travel_end_date
TripService.calc_end_date(self.trip_length, self.created_at)
end
def trip_over?
travel_end_date <= Time.zone.now.end_of_day
end
end
这个TripService
:
class TripService
def calc_end_date(trip_length, start_date)
trip_length.gsub("_day", "").to_i
start_date.beginning_of_day + interval.days
end
end
和BookingService
:
class BookingService
def self.past_trips
Booking.select { |booking| booking.trip_over? }
end
end
当你跑步时,有成千上万的预订需要查看BookingService.past_trips
这会导致查询效率低下。
我想把这一点转移到SQL上,并研究了使用SQL case语句来改进这一点——这对于这个查询来说会是什么样子?
特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报