【问题标题】:MySQL - ranking by count() and GROUP BYMySQL - 按 count() 和 GROUP BY 排名
【发布时间】:2012-04-23 18:49:06
【问题描述】:

我有我的 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

我怎样才能让查询给出正确的排名?

【问题讨论】:

  • 那是ORDER BY count(id) DESC 对吧?
  • @mellamokb 它不适用于 DESC 和 ASC
  • 如果两个或更多用户的帖子数量相同,您希望发生什么?
  • @pilcrow hm,我认为这没关系,它应该只为每个 uid 次要的 ist 排序

标签: mysql count group-by rank


【解决方案1】:

您需要先将整个结果集按用户 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”子句时遇到问题,我会将其包装起来,然后应用 where...

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

【讨论】:

  • 嗯,指定uid是否可以只返回一行?
  • @Ninov,是的,只需添加到查询的最外层... HAVING prequery.uid = IDOfPersonWanted
  • @DRapp,你确定有指导吗?如果我将其添加到实质上相似的 MySQL ROW_NUMBER hack,我会得到 ERROR 1463 (42000): Non-grouping field ... is used in HAVING clause
  • Hm 这为 uid 1 返回 rank=1,为所有其他 uid 返回 (Null)... edit: 它为每个 uid 返回 rank=1,其中包含任何帖子:(
  • @ninov,修改后将答案再上一层。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-17
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-06
相关资源
最近更新 更多