表加入Ruby on Rails

时间:2012-05-02 06:52:41

标签: mysql ruby-on-rails ruby database

如果我有两个单独的表设置如下:

University 1:

student   major   year    gpa


University 2:

student   major   address   gpa   hometown  extra curriculars

有没有办法可以让专业按照该专业的顶级gpa排序?对不起,这可能是一个简单的问题,但我对Ruby on Rails相当新。谢谢!

2 个答案:

答案 0 :(得分:0)

这是SQL做得很好的,所以你可以在SQL中做到这一点。 (在得到结果之后在ruby代码中执行此操作很清楚,你应该能够弄明白。)

SELECT *
FROM university
GROUP BY major
ORDER BY MAX(gpa) DESC

所以,在Rails 2.x

University.find(:group => "major", :order => "MAX(gpa) DESC")

在Rails 3.0中

University.group("major").order("MAX(gpa) DESC")

答案 1 :(得分:0)

如果您希望在两所大学中获得主要GPA,那么SQL就像这样,例如:

SELECT major, MAX(GPA) AS GPA FROM
  (SELECT major, MAX(GPA) AS GPA FROM UNIVERSITY_1
   GROUP BY major
   UNION
   SELECT major, MAX(GPA) AS GPA FROM UNIVERSITY_2
   GROUP BY major)
GROUP BY major
ORDER BY GPA DESC

我不确定如何在Arel中表达该查询 - 不确定它是如何进行联合的,这将是很好的知道。在此期间,您始终可以使用find_by_sql从原始SQL获取结果集。

编辑:

有点Ruby-er / Railsier的方法可能是:

u_one = UniversityOne.maximum :gpa, :group => 'major'
u_two = UniversityTwo.maximum :gpa, :group => 'major'
u_combined = u_one.merge(u_two) { |k, one, two| [one,two].max }

u_combined最终成为一个散列,主要作为关键,大学的最大gpa作为价值。