开发者

Ordering a top ten query

Thanks for reading.

I'm trying to write a query to list the names of people who have recevied the mo开发者_如何学JAVAst votes using two tables:

-------
votes
-------
vote_id, giver_user_id, receiver_user_id, datetime

etc..

-------
users
-------

user_id, name, surname

etc...

So far I have:

$top_query = "SELECT * FROM vote, user WHERE vote.receiver_user_id = user.user_id GROUP BY receiver_user_id  ";

This kind of works, but it doesn't list the user with the most votes at the top of the list.

How can I order it this way?

Thank you.

OP


SELECT  u.*, COUNT(vote_id) AS votes_count
FROM    users u
LEFT JOIN
        votes v
ON      v.receiver_user_id = u.user_id
GROUP BY
        u.user_id
ORDER BY
        votes_count DESC


You can use the ORDER BY clause. With the keyword "asc" or "desc"

Something like :

ORDER BY vote_count DESC

Mysql reference :

http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html


This will group by receiver and order by votes in descending order:

    select receiver_user_id, count(1) vote_count
      from vote, user 
     where vote.receiver_user_id = user.user_id 
  group by receiver_user_id 
  order by 2 desc
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜