排名查询在mysql中无法正常工作

时间:2014-05-14 09:11:32

标签: php mysql ranking

我有这个问题,试图根据每个用户获得的肯定投票总数进行排名。问题是排名是由用户ID进行的,而不是由VOTES进行的。问题是因为GROUP BY,但我必须使用它,因为一个id在voted_id部分中多次出现。

我想知道你是否有一些解决方案?

select 
  a.voted_id, 
 (select 
    count(b.state) 
  from 
   user_vote as b 
  where 
   b.state=1 and b.voted_id=a.voted_id) as votes, 
 @rank:=@rank+1 as ranking from user_vote as a,
 (select @rank:=0)as rank 
where
  a.state=1 
group by 
 a.voted_id 
order by 
 votes asc;

所以问题在于排名是由voted_id完成而非投票。

1 个答案:

答案 0 :(得分:0)

这有什么好处?没有DDL& amp;很难看到你在哪里一些样本数据...

select voted_id,
       votes,
       @rank:=@rank + 1 as rank
from
(
 select voted_id,count(*) as votes
 from user_vote
 where state=1
 group by voted_id
 order by votes desc
) t
join (select @rank:=0) r;