我有我的mysql表帖子,我的论坛的所有帖子都存储在那里.就像这样:

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

现在我想显示用户配置文件的排名(帖子数量排名).我尝试过这样的事情:

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

但它返回的不是正确的数据. uid和count(id)匹配,但排名是错误的.
我的条目是:

rank     uid     count(id)
  1        1        214

我是用户1,我有214个帖子,但这不是1级.
还有其他条目,如:


rank     uid     count(id)
  8       22        674

如何才能使查询得出正确的排名?

解决方法:

您需要先按用户ID分组并订购整个结果集…然后应用排名

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

为了得到一个特定的人,并尝试“HAVING”条款的问题,我会把它包起来,然后应用一个…

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

标签: count, mysql, rank, group-by

相关文章推荐

添加新评论,含*的栏目为必填