在我的 Rails 应用程序中,我有一个名为 HealthcareCenter 的表。
我想根据以下顺序列出 HealthcareCenter(我有分页,每页应列出 50 条记录)。
- 推荐数量(如果用户登录)
- 评分(高评分优先)
- 距离(第一个设定距离应小于 25 公里,第二个距离在 25 到 100 之间,第三个任意距离,但按升序排列)
我将通过下图进行解释
在图像中我们可以看到 5 个诊所,如图所示 sql 应该订购诊所
我已经写了
HealthcareCenter.where("healthcare_centers.name LIKE ?", "%#{query}%")
.where(type_id: type_id)
.order("healthcare_centers.overall_rating DESC")
.calculate_distance2a(lat, lon)
.order("distance")
.order("healthcare_centers.name")
.offset(offset)
.limit(limit)
def self.calculate_distance2a(orig_lat, orig_lon, dist = nil)
lat1, lon1, lat2, lon2 = the_square(orig_lat, orig_lon, dist)
self.select(" healthcare_centers.id,
ROUND(
6371 * 2 * ASIN ( SQRT (
POWER( SIN((#{orig_lat} - healthcare_centers.latitude)*pi()/180 / 2),2)
+ COS(#{orig_lat} * pi()/180)
* COS(healthcare_centers.latitude *pi()/180)
* POWER(SIN((#{orig_lon} - healthcare_centers.longitude) *pi()/180 / 2), 2)
) ),2) as distance"
)
.where("healthcare_centers.longitude between #{lon1} and #{lon2}")
.where("healthcare_centers.latitude between #{lat1} and #{lat2}")
.order("distance")
end
此查询为我提供了具有高评级的诊所列表(因为目前我正在检查用户未登录),但第一个结果为我提供了超过 25KM
因为在我的数据库上超过25KM有很高的评价
您能否指导我如何包含这些距离条件
1) <= 25
2) > 25 && <= 100
3) > 100(应按升序排列)
考虑如果小于 25KM,我们有 2 个诊所。诊所 A 4.3(评级),2 公里距离,诊所 B 3(评级),1.5 公里(基于评级)诊所 A 应列在顶部。
最佳答案
您应该将距离计算为列别名,然后
HealthcareCenter.where("healthcare_centers.name LIKE ?", "%#{query}%")
.where(type_id: type_id)
.order("healthcare_centers.overall_rating DESC,
distance,
healthcare_centers.name")
关于mysql - 如何在 Rails 中应用多个 Order by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44651912/