I'm having a hard time converting this SQL query to ActiveRecord. Here's my SQL.
SELECT distinct stc_term_gpa,
user_id,
lesley_id,
first,
last,
FROM lesley_grades
ORDER BY user_id
and this returns 437 rows - which is want I want. I have no problems runnings this in SQL
But when I try to run this in Rails in the Console:
LesleyGrade.select(:stc_term_gpa, :user_id, :lesley_id, :first, :last).distinct.order(:user_id)
I verified the count in rails
LesleyGrade.select(:stc_term_gpa, :user_id, :lesley_id, :first, :last).distinct.order(:user_id).count(:all)
I return 1440 rows - which is not what I want...that's all the data rows in my DB.
What's going on?
UPDATE
This is strange:
When I run the active record query in Rails Console and get the count 1440
LesleyGrade.select(:stc_term_gpa, :user_id, :lesley_id, :first, :last).distinct.order(:user_id).count(:all)
I check the SQL in the console (the one that ActiveRecord produces) and this is what it produces:
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
When I run the above SQL in a SQL client I get the 437 rows. Again a discrepancy.
HOWEVER when I'm playing with the SQL that rails produces, and take the above statement and add in lesley_grades.id in the projection on my own accord and running raw SQL in a client like this, I get 1440 row (shouldn't it still be getting 437 even if I place the ID there?)
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
So I guess the question is does ActiveRecord some how use the ID for something in the a query sneakily, which is why I'm receiving 1440? How do I get my distinct 437 rows?
You can still use 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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.