Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 DISTINCT QUERY

Tags:

Have a User, UserBadge, and Badge table. They are connected through a has_many through. A user can have multiple of the same badge but I want to query a unique list.

@user.badges.select("DISTINCT id").order("created_at DESC") 

It's throwing an error:

SQLite3::SQLException: near "DISTINCT": syntax error: 

What would be the proper syntax?

EDIT: ADDED WHOLE ERROR

SQLite3::SQLException: near "DISTINCT": syntax error: SELECT "badges".*, DISTINCT badges.id FROM "badges" INNER JOIN "userbadges" ON "badges".id = "userbadges".badges_id WHERE (("userbadges".user_id = 1)) 

Could it be the comma between select and distinct?

like image 739
John Avatar asked May 05 '11 17:05

John


2 Answers

DISTINCT needs to be straight after the SELECT i.e.

SELECT DISTINCT(badges.id), "badges".* FROM "badges" INNER JOIN "userbadges" ON "badges".id = "userbadges".badges_id WHERE (("userbadges".user_id = 1)) 

Try:

@user.select("DISTINCT(badges.id), badges.*").badges.order("badges.created_at DESC") 

PostgreSQL requires you have an order statement for the distinct field:

@user.select("DISTINCT(badges.id), badges.*").badges.order("badges.id").order("badges.created_at DESC") 
like image 167
Mike Neumegen Avatar answered Oct 07 '22 02:10

Mike Neumegen


Could try using group

@user.badges.group(:id) 
like image 29
Kelend Avatar answered Oct 07 '22 02:10

Kelend