mysql count排序_MySQL - 按count()和GROUP BY排序

bd96500e110b49cbb3cd949968f18be7.png

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?

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值