MySQL - ranking by count() and GROUP BY

混江龙づ霸主 提交于 2019-12-05 02:47:06

问题


I've got my mysql table posts, where all posts of my forum are stored. It's like this:

id      uid      thread      post      title      text      time
(int)   (int)    (varchar)   (int)     (varchar)  (text)    (int)

Now I want to show the rank (ranking of number of posts) on the user profiles. I've tried something like this:

set @rownum := 0;
SELECT @rownum := @rownum + 1 AS rank, uid, count(id)
FROM `posts` GROUP BY uid ORDER BY count(id)

But it returns not the right data. The uid and count(id) match, but the rank is wrong. My entry is like:

rank     uid     count(id)
  1        1        214

I'm user 1, and I've got 214 posts, but that's not rank 1. There are other entries like:

rank     uid     count(id)
  8       22        674

How can I get the query to put out the right rank?


回答1:


You need your entire result set grouped by user ID first and ordered... then apply the ranking

select
      @rownum := @rownum +1 as rank,
      prequery.uid,
      prequery.PostCount
   from
      ( select @rownum := 0 ) sqlvars,
      ( SELECT uid, count(id) postCount
           from posts
           group by uid
           order by count(id) desc ) prequery

To get for a specific person, and problem attempting the "HAVING" clause, I would then wrap it up and then apply a where...

select WrappedQuery.* 
   from ( entire query from above ) WrappedQuery
   where WrappedQuery.uid = SinglePerson


来源:https://stackoverflow.com/questions/10286418/mysql-ranking-by-count-and-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!