MYSQL SELECT rank of user (more than x & less than y)

前端 未结 2 933
孤独总比滥情好
孤独总比滥情好 2021-01-16 17:39

I\'m a bit stuck with a php/Mysql Query. I got 2 tables :

  table_users              table_ranks
----------------    ------------------------
| id  | points          


        
相关标签:
2条回答
  • 2021-01-16 17:59

    give this a try, a little bit messy due to table design,

    SELECT  u.*, r.name
    FROM    table_users u
            INNER JOIN
            (
                SELECT x.name, 
                       x.points_needed start_point, 
                       COALESCE(y.points_needed - 1, 2000000) end_point
                FROM
                (
                  SELECT name, points_needed, @rank:=@rank+1 ranks
                  FROM table_ranks a, (SELECT @rank:=0) b
                  ORDER BY points_needed
                ) x
                LEFT JOIN 
                (
                  SELECT name, points_needed, @rank1:=@rank1+1 ranks
                  FROM table_ranks a, (SELECT @rank1:=0) b
                  ORDER BY points_needed
                ) y ON x.ranks+1 = y.ranks
            ) r ON u.points BETWEEN r.start_point AND r.end_point
    
    • SQLFiddle Demo
    0 讨论(0)
  • 2021-01-16 18:11

    You can do it like this

    SELECT
      tu.id,
      tr.name,
      tu.points
    FROM table_ranks as tr
      LEFT JOIN (SELECT * FROM table_ranks LIMIT 1,69596585953484) as l
        ON l.points_needed = (SELECT MIN(points_needed) FROM table_ranks WHERE points_needed > tr.points_needed limit 1)
      LEFT OUTER JOIN table_users AS tu ON tu.points >= tr.points_needed AND tu.points < l.points_needed
    WHERE tu.id IS NOT NULL
    group by tu.id
    

    Fiddle

    Output

    -------------------------
    | id  | points   | name |
    -------------------------
    | 1   |   lvl0   | 2    |
    | 2   |   lvl1   | 10   |
    | 3   |   lvl2   | 21   |
    | 4   |   lvl2   | 29   |
    -------------------------
    
    0 讨论(0)
提交回复
热议问题