MySQL查询帮助按ID查找排名

时间:2011-06-01 01:42:46

标签: mysql sql ranking

我正在尝试修改以下查询以查找特定视频的排名,而且我没有太多运气可以有人建议解决方案吗?

  SELECT videoid wins/loses as win_loss, 
         @curRank := @curRank + 1 AS rank
    FROM cb_video, 
         (SELECT @curRank := 0) r  
ORDER BY wins/loses DESC

我尝试过这样的子查询,但它失败了:

SELECT rank 
  FROM (SELECT videoid wins/loses as win_loss, 
               @curRank := @curRank + 1 AS rank 
          FROM cb_video, 
               (SELECT @curRank := 0) r  
      ORDER BY wins/loses DESC) 
 WHERE videoid = 116

同样将videoid添加到没有子查询的WHERE子句中总是将排名显示为#1位置,因为它只返回一行:

  SELECT videoid wins/loses as win_loss, 
         @curRank := @curRank + 1 AS rank 
    FROM cb_video, 
         (SELECT @curRank := 0) r 
   WHERE videoid = 116 
ORDER BY wins/loses DESC

有关如何将结果限制为特定ID但仍保留排名的任何想法?仅供参考,如果有帮助,我会保留两列(胜利和失败)。

3 个答案:

答案 0 :(得分:1)

尝试这样的事情:

SELECT videoid, rank FROM (SELECT videoid, wins/loses as win_loss, @curRank := @curRank + 1 AS rank FROM cb_video, (SELECT @curRank := 0) r  ORDER BY wins/loses DESC) s WHERE videoid = 116

答案 1 :(得分:1)

SELECT a.videoid, 
(SELECT COUNT(*) FROM cb_video b 
 WHERE a.videoid !=b.videoid 
 AND (b.wins/b.loses) > (a.wins/a.loses))+1 AS rank
FROM cb_video a
WHERE a.videoid = 116

答案 2 :(得分:1)

我已经在你所描述的类似表格创建的简单子集上进行了测试... 它返回ONE视频及其整个集合的实际最终排名......

select *
   from ( SELECT 
              videoid, 
              wins, 
              losses, 
              wins/losses,       
              @curRank := @curRank +1 Rank
           FROM 
              cb_video,
              ( select @curRank := 0 ) r
           order by 
              wins/losses desc ) PreQuery
    where
       PreQuery.VideoID = 116