Sql 根据关联记录的比较排序查询
我要从DB中找到男人,我要他们根据长子的年龄来订购。这里有一个例子Sql 根据关联记录的比较排序查询,sql,ruby-on-rails,ruby,postgresql,activerecord,Sql,Ruby On Rails,Ruby,Postgresql,Activerecord,我要从DB中找到男人,我要他们根据长子的年龄来订购。这里有一个例子 class Man has_many :sons # id end class Son belongs_to :man # id, man_id, age end 如何让ActiveRecord执行此操作 编辑 当我尝试执行Man.joins(:sons.order(“sons.age DESC”).uniq时,我得到了无效的SQL first_man = Man.create first_man.son
class Man
has_many :sons
# id
end
class Son
belongs_to :man
# id, man_id, age
end
如何让ActiveRecord执行此操作
编辑
当我尝试执行Man.joins(:sons.order(“sons.age DESC”).uniq时,我得到了无效的SQL
first_man = Man.create
first_man.sons.create(age: 10)
first_man.sons.create(age: 5)
second_man = Man.create
second_man.sons.create(age: 20)
second_man.sons.create(age: 5)
third_man = Man.create
third_man.sons.create(age: 19)
third_man.sons.create(age: 8)
Man.order('[some order]').to_a
=> [second_man, third_man, first_man]
没有试过,但我想这应该行得通
ActiveRecord::StatementInvalid:
PG::InvalidColumnReference: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...sons"."man_id" = "men"."id" ORDER BY sons...
^
: SELECT DISTINCT "men".* FROM "men" INNER JOIN "sons" ON "sons"."man_id" = "men"."id" ORDER BY sons.age DESC LIMIT 15
试试这个
Man.includes(:sons).order("sons.age").to_a
已更新
也许这会有帮助,但这很难看
Man.joins(:sons).order('sons.age DESC').uniq
@拉法:你指的是什么?对不起,我当时才意识到,他是第一个。因此,我删除了我的答案。
Son.order('age DESC').map(&:man).uniq