SQL(postgres)到ActiveRecord查询

时间:2015-05-07 21:36:35

标签: ruby-on-rails postgresql activerecord

我很难将此SQL查询转换为ActiveRecord。这是我的SQL。

SELECT distinct stc_term_gpa,
    user_id,
    lesley_id,
    first,
    last,
FROM lesley_grades
ORDER BY user_id

这会返回437行 - 这是我想要的。我在SQL

中运行它没有问题

但是当我尝试在控制台的Rails中运行它时:

LesleyGrade.select(:stc_term_gpa, :user_id, :lesley_id, :first, :last).distinct.order(:user_id)

我在rails中验证了计数

LesleyGrade.select(:stc_term_gpa, :user_id, :lesley_id, :first, :last).distinct.order(:user_id).count(:all)

我返回1440行 - 这不是我想要的......这是我数据库中的所有数据行。

发生了什么?

更新

这很奇怪:

当我在Rails控制台中运行活动记录查询并获得计数1440

LesleyGrade.select(:stc_term_gpa, :user_id, :lesley_id, :first, :last).distinct.order(:user_id).count(:all)

我检查控制台中的SQL(ActiveRecord生成的SQL),这就是它产生的:

SELECT DISTINCT 
    "lesley_grades"."stc_term_gpa", 
    "lesley_grades"."user_id", 
    "lesley_grades"."lesley_id", 
    "lesley_grades"."first", 
    "lesley_grades"."last" 
FROM "lesley_grades"   
ORDER BY "lesley_grades"."user_id" ASC

当我在SQL客户端中运行上述SQL时,我获得了437行。再次出现差异。

HOWEVER 当我正在使用rails生成的SQL时,并采用上述语句并在我自己的投影中添加lesley_grades.id并在客户端中运行原始SQL像这样,我得到了1440行(即使我把ID放在那里,它仍然会得到437?)

SELECT DISTINCT 
    "lesley_grades"."stc_term_gpa", 
   **"lesley_grades"."id"**, 
    "lesley_grades"."user_id", 
    "lesley_grades"."lesley_id", 
    "lesley_grades"."first", 
    "lesley_grades"."last"
FROM "lesley_grades"
ORDER BY "lesley_grades"."user_id" ASC

所以我想问题是ActiveRecord是如何偷偷摸摸地使用ID来查询某些内容的,这就是我收到1440的原因?如何获得我独特的437行?

1 个答案:

答案 0 :(得分:0)

您仍然可以使用find_by_sql metod

query = "SELECT distinct stc_term_gpa, user_id,lesley_id,first,last
         FROM lesley_grades
         ORDER BY user_id"
expectedResult = LesleyGrade.find_by_sql(query)