Mysql选择查询计数直到达到条件

时间:2016-07-14 06:47:41

标签: mysql count conditional-statements limit

我有用户名单和游戏ID。我需要根据最大lb_point的游戏顺序找到指定用户的等级。下面是我的表。

lb_id    user_id   game_id   room_id   lb_point
------------------------------------------------
1         1        2         1         670     
2         1        1         2         200     
3         1        2         2         650     
4         1        1         1         400     
5         3        2         1         700     
6         4        2         5         450     
7         2        1         3         550     
8         2        1         1         100     
9         1        1         1         200     

我已经通过使用PHP代码完成了这项工作,其工作正常如下。

$game_id = 2;
$user_id = 1;
$query_rnk = $this->db->query('SELECT user_id AS uid FROM leader_board WHERE game_id = "'.$game_id.'" GROUP by user_id ORDER BY lb_point DESC');
        if ($query_rnk->num_rows() > 0){
            $j=1;
            foreach($query_rnk->result() as $row_rnk){
                if($row_rnk->uid == $user_id){
                    $rnk_status = 1;
                    break;
                }
            $j++;
            }
            if($rnk_status == 1){
                $resp['rank'] = $j;
            }
        }

答案是:2。

但我需要通过使用一个查询来找到它。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

您可以使用选择计算正确选择的行数

select count(*) 
from (
      select distinct user_id
      from leader_board 
      where   lb_point >= (select  max( lb_point )
             from leader_board 
             where user_id = 1   
             and game_id = 2 )
      and game_id = 2
) t

答案 1 :(得分:0)

如果您想获得user_id = 1的排名,请尝试以下操作:

SELECT urank
FROM (
    SELECT user_id AS uid, @rank := @rand + 1 AS urank
    FROM leader_board
    CROSS JOIN (SELECT @rank := 0) t
    WHERE game_id = '$game_id'
    GROUP by user_id
    ORDER BY lb_point DESC
) tmp
WHERE uid = '$user_id'

答案 2 :(得分:0)

SELECT count(*)+1 as Rank from (select lb_point from games where game_id =2 order by lb_point DESC) as list where list.lb_point > (select max(lb_point) from games where user_id = 1 and game_id = 2)

这将在game_id = 2中给出user_id = 1的等级2,这是您提到的答案。