Ranking joint positions in MySQL

后端 未结 3 1767
孤街浪徒
孤街浪徒 2020-12-04 04:30

Below is what I have

  userid score 
    1       8    
    2       5    
    3       4    
    4       4    
    5      10    
    6       3  
相关标签:
3条回答
  • 2020-12-04 04:41

    I think that you could try it using variables, which looks easier. Something like this:

    SELECT userid, score, @rownum:=@rownum+1 as position
    FROM fschema.mytab3 u1, (SELECT @rownum:=0) r
    ORDER BY score;
    

    (Currently I'm unable to check MySql queries, please, excuse me if there is some error)

    0 讨论(0)
  • 2020-12-04 04:51

    What about this?

    SELECT userid, score, 
    (SELECT COUNT(distinct u2.score) FROM fschema.mytab3 u2 
    WHERE 
    u2.score > u1.score) + 1 AS position FROM fschema.mytab3 u1
    ORDER BY position
    
    0 讨论(0)
  • 2020-12-04 05:00

    Try this one -

    SELECT
      *,
      @r:=IF(@score IS NULL OR @score <> score, @r+1, @r) position, @score:=score
    FROM
      fschema.mytab3,
      (SELECT @r:=0, @score:=NULL) t
    ORDER BY
      score DESC, userid
    
    0 讨论(0)
提交回复
热议问题