我有我的mysql表posts
,其中存储了我论坛的所有帖子。就像这样:
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
如何让查询得出正确的排名?
答案 0 :(得分:6)
您需要先按用户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