6

I have a Rails 3 app which keeps high scores. I'm hosting it on Heroku which uses postgresql as the db.

I need to extract the top scores from the scores table. The table has columns score and user_id. It was working in mysql with the following:

Score.order('score DESC').group('user_id').limit(25)

This ranks each user's top score.

When I put the app on Heroku, I get the following psql error PGError: ERROR: column "scores.id" must appear in the GROUP BY clause or be used in an aggregate function

I've read around but haven't found a clear answer. What is the most optimal way to recreate the above query to work with PostgreSQL?

Thanks!

Tim

1
  • I'm trying to use DISTINCT ON as stated by others. Score.select('DISTINCT ON (user_id) id, user_id, score').order('user_id, score DESC').limit(25) and I get the following error: "PGError: ERROR: column id_list.alias_0 does not exist LINE 1: ... AS id_list ORDER BY id_list.al...". I'm not even stating a column with the name of 'id_list' so I don't get why that's coming up. Commented Dec 28, 2010 at 7:32

2 Answers 2

2

That means your select query is selecting the "id" column but not including it in the group by clause. I'm not familiar with rails but could it be selecting * or all columns?

Sign up to request clarification or add additional context in comments.

Comments

0

Could you do

select id, max(score) group by id;

4 Comments

I'd like to see the query that got the error, because that query up there should generate no error.
Score.select('user_id, score, max(score)').group('user_id').limit(25) works with mysql but shoots off the same error with postgresql.
That is not the same as my query, you're asking for score without grouping by it or using an aggregate. make it something like score.select('user_id,max(score)').group('user_id').limit(25) If you need all the scores then a group by isn't the right choice anyway.
Hey Scott, first of all, thanks for your replies. Your query works but I need to list the scores. If I don't use 'score' in the select statement like I did above, I get the error 'missing attribute: score'. If I call @high_scores = Score.select('user_id,max(score)').group('user_id').limit(25), I can't call @high_score.score. Is there a way to resolve this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.