Mysql 我可以在WHERE语句中使用自定义方法吗?

Mysql 我可以在WHERE语句中使用自定义方法吗?,mysql,sql,ruby-on-rails,ruby,activerecord,Mysql,Sql,Ruby On Rails,Ruby,Activerecord,我的Rails应用程序中有以下两种型号: create_table "projects", force: :cascade do |t| ... t.float "latitude", limit: 24, default: 0.0 t.float "longitude", limit: 24, default: 0.0 用户: 我有一个自定义类: class CalculusAid public # point_one and point

我的Rails应用程序中有以下两种型号:

create_table "projects", force: :cascade do |t|
  ...
  t.float    "latitude",   limit: 24,    default: 0.0
  t.float    "longitude",  limit: 24,    default: 0.0
用户:

我有一个自定义类:

class CalculusAid
  public
    # point_one and point_two are arrays of [latitude, longitude]

    def self.distance point_one, point_two

    first_point_latitude,  first_point_longitude  = point_one
    second_point_latitude, second_point_longitude = point_two

    latitude_difference_in_radians = (first_point_latitude - second_point_latitude).to_radians
    longitude_difference_in_radians = (first_point_longitude - second_point_longitude).to_radians

    #Math stuff
    a = Math.sin(latitude_difference_in_radians/2) * Math.sin(latitude_difference_in_radians/2) +
    Math.cos(first_point_latitude.to_radians) * Math.cos(second_point_latitude.to_radians) *
    Math.sin(longitude_difference_in_radians/2) * Math.sin(longitude_difference_in_radians/2);
    c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

    distance_in_kilometers = 6371 * c; # Multiply by 6371 to get Kilometers
    return distance_in_kilometers
 end
 ...
我不想做的是返回5个距离用户0到50公里的随机项目,我想用这样的方法来实现

class User < ActiveRecord::Base
  def get_nearby_projects
     @nearby_projects = User.joins(:projects).where(CalculusAid.distance([self.last_longitude],self.last_latitude][project.longitude,project.latitude]) < 50).limit(5).order("RAND()")
  end
class用户
但是我不知道我是否可以在where语句中使用自定义方法,或者语法是否正确。

为什么不简单地说一下“where range<50km”。 另外,您可以在Order语句中调用random

SELECT a,b,c, ... 
FROM table
WHERE range < 50
ORDER BY RAND()
LIMIT 5;
选择a、b、c。。。
从桌子上
其中范围<50
兰德订单()
限值5;

这是不可能直接实现的,因为Rails只构建一个由MySQL执行的查询,并从DB服务器获取结果。这是一个原子操作,不能将lambda传递给MySQL来过滤结果

但MySQL有:


@nearely\u projects=ActiveRecord::Base.connection.execute我没有range方法我不能用distance函数替换50>6371*(SIN…)吗?不,你应该用纯SQL重写它。好的,如果没有更好的方法,我会用我不知道的方法。也许未来的访问者会建议更好的方法。
SELECT a,b,c, ... 
FROM table
WHERE range < 50
ORDER BY RAND()
LIMIT 5;
@nearby_projects = ActiveRecord::Base.connection.execute <<-SQL
  SELECT * 
  FROM users
    JOIN projects ON (???) -- unclear from the code you’ve pasted
  WHERE
    50 > 6371 * (SIN(users.last_latitude + .......
SQL