Rails相关子查询相同的表

时间:2014-07-09 05:12:23

标签: sql ruby-on-rails ruby oracle activerecord

我的问题是将以下SQL查询转换为ActiveRecord Rails:

SELECT H1.* 
FROM USERS H1 
WHERE DAYS = (SELECT MAX(DAYS) FROM USERS H2
WHERE H1.COUNTRY = H2.COUNTRY
AND H1.NAME = H2.NAME
AND H1.MARKET = H2.MARKET
AND H1.TALL = H2.TALL)

我将此转换为Rails ActiveRecord的最大问题是相关子查询在同一个表上查询 - " USERS"并且在ActiveRecord中对表名进行别名是非法的。

Find_by_sql对我来说也不是一个选项,因为它不能与其他ActiveRecord函数一起使用。

2 个答案:

答案 0 :(得分:2)

您可以写为

User.select("view.*")
    .from("User.group(:name, :country, :market, :tall)
    .maximum(:days), :view)")
    .where("days = ?", view.days)

查看#from方法,了解正在发生的事情。

答案 1 :(得分:1)

User.all(:select    => "users.COUNTRY, users.NAME, users.MARKET, users.TALL, users.DAYS",
         :joins     => "JOIN users AS H2 
                              ON H2.COUNTRY = users.COUNTRY AND 
                                 H2.NAME = users.NAME AND 
                                 H2.MARKET = users.MARKET AND 
                                 H2.TALL = users.TALL " ,
         :conditions => ["users.DAYS = H2.MAX(DAYS) "]
).each do |user|
  p "COUNTRY : #{user.COUNTRY}"
  p "NAME : #{user.NAME}"
  p "MARKET : #{user.MARKET}"
  p "TALL : #{user.TALL}"
  p "DAYS : #{user.DAYS}"
end