poipu
December 20, 2006, 9:18pm
1
hi, i need to fetch the users with the most airtcles in my table.
i am starting with this…
@temp = Howto.find_by_sql ([“select user_id from Howtos” ])…
now i have an array with all the user_ids…but i need to do something
like this…
@temp = Howto.find_by_sql ([“select user_id from Howtos Order by
user_id.count limit 10” ])…
…any suggestions? thanks.
poipu
December 20, 2006, 9:29pm
2
I assume a user has_many howtos and a howto belongs_to a user in the
respective models
@temp = User.find(:all, :select => “users.id,users.username,
count(howtos.id)
as numhowtos”, :joins => “left join howtos on users.id =
howtos.user_id”,
:order => “numhowtows DESC”)
Adam
poipu
December 20, 2006, 10:01pm
3
hi thanks for the help! unfortunantley my debugging skills with sql is
limited. i am recieving this error
Mysql::Error: #42000Mixing of GROUP columns (MIN(),MAX(),COUNT(),…)
with no GROUP columns is illegal if there is no GROUP BY clause: SELECT
users.id, users.login, count(howtos.user_id) as numhowtos FROM users
left join howtos on users.id = howtos.user_id ORDER BY numhowtos DESC
i am using this
@temp = User.find(:all,
:select => “users.id, users.login,
count(howtos.user_id) as numhowtos”,
:joins => “left join howtos on users.id =
howtos.user_id”,
:order => “numhowtos DESC”
)
users is my table name and each user hasn many howtos and howto belongs
to user…
thanks!
unknown wrote:
I assume a user has_many howtos and a howto belongs_to a user in the
respective models
@temp = User.find(:all, :select => “users.id,users.username,
count(howtos.id)
as numhowtos”, :joins => “left join howtos on users.id =
howtos.user_id”,
:order => “numhowtows DESC”)
Adam
poipu
December 20, 2006, 11:22pm
4
poipu
December 20, 2006, 10:48pm
5
@temp = Howto.find_by_sql ([“select user_id from Howtos Order by
user_id.count limit 10” ])…
Here is a description of how to use MySQL count() function.
http://dev.mysql.com/doc/refman/5.0/en/counting-rows.html
You probably want to do something like:
select count(user_id), user_id from Howtos
group by user_id
This is an aggregate query, so you’d use GROUP
rather than ORDER. hth
poipu
December 21, 2006, 12:05am
6
i tried this…
@topusers= User.find_by_sql(“SELECT users.id,users.login,
COUNT(#{Howto.id}) FROM Users GROUP BY users.id”)
but my count for each user is set to one and not the proper count…
when i change the Howto.id to Howto.user_id i get a ’ stack level too
deep’… i also implemented the method
def user_id
user_id
end
in the howto model class.
poipu
December 21, 2006, 6:44am
7
hey everyone…thanks for the help… i finally found something that
seems to work but i dont quite understand yet how mysql works…
this is what i did…
User.find_by_sql (“SELECT Users.id, COUNT(Howtos.user_id) FROM Howtos,
Users WHERE Howtos.user_id = Users.id GROUP BY Users.id”)