简体   繁体   中英

What's the difference between Rails active record's select and group?

I've been reading through tutorials on Rails' active record model operations. And I'm a little confused on the difference between .select and .group. If I wanted to get all the names of all my users in table User I believe I could do:

myUsers = User.select(:name)

so how would that be different from saying:

myUsers = User.group(:name)

thanks,

Will

The two differ like this:

User.select(:name)

is equivalent to this SQL statement

SELECT name from users;

and

User.group(:name)

is equivalent to

SELECT * from users GROUP BY name;

The difference is that with select(:name) you are taking all rows ordered by id , but only with column name . With group(:name) you are taking all rows and all columns, but ordered by column name .

User.pluck(:name) will be the fastest way to pull all the names from your db.

There is #to_sql method to check what DB query it is building. By looking at the DB query, you can confirm yourself what is going on. Look the below example :-

arup@linux-wzza:~/Rails/tv_sms_voting> rails c
Loading development environment (Rails 4.1.4)
>> Vote.group(:choice).to_sql
=> "SELECT \"votes\".* FROM \"votes\"  GROUP BY choice"
>> Vote.select(:choice).to_sql
=> "SELECT \"votes\".\"choice\" FROM \"votes\""
>>

Now it is clear that Vote.select(:choice) is actually, SELECT "votes"."choice" FROM "votes" , which means, select choice column from all rows of the table votes .

Vote.group(:choice) is grouping the rows of the votes table, based on the column choice and selecting all columns.

If I wanted to get all the names of all my users in table User.

Better is User.pluck(:name) .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM