query that outputs that # of unique records per field in a model?
Given a Model like:
Con开发者_如何学JAVAtact (id, user_id, xxx, xxxxxxx)
I would like to have a query that outputs that # of unique user_id records in the Contact model? Any thoughts on how to write this?
Thanks
There are several ways of doing this in SQL, but if you want to try to keep within the ORM provided by ActiveRecord as much as possible I think the following is the closest you are going to get:
@user_ids = Contact.select('DISTINCT user_id').all
@user_ids
will then be an array of all the user ids referenced from records in the contact table. If you want to know how many there are you can just call @user_ids.count
.
Update: Another way of doing this that provides even more information without the overhead of instantiating each object and avoids writing SQL is as follows:
Contact.group('user_id').count #=> { 1 => 3, 2 => 4, 3 => 10 }
As you can see, the response is a hash with the user ids as keys and the quantity for each user as the value. You can get the number of unique user ids with another .count
:
Contact.group('user_id').count.count #=> 3
Here are some alternative ways to do it:
Contact.count('user_id', :distinct => true)
# SELECT COUNT(DISTINCT "contacts"."user_id") FROM "contacts"
Contact.count('DISTINCT user_id')
# SELECT COUNT(DISTINCT user_id) FROM "contacts"
精彩评论