With MySQL, how can I generate a column containing the record index in a table?

前端 未结 8 1768
轻奢々
轻奢々 2020-11-21 23:57

Is there any way I can get the actual row number from a query?

I want to be able to order a table called league_girl by a field called score; and return the username

8条回答
  •  鱼传尺愫
    2020-11-22 00:37

    Assuming MySQL supports it, you can easily do this with a standard SQL subquery:

    select 
        (count(*) from league_girl l1 where l2.score > l1.score and l1.id <> l2.id) as position,
        username,
        score
    from league_girl l2
    order by score;
    

    For large amounts of displayed results, this will be a bit slow and you will want to switch to a self join instead.

提交回复
热议问题