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

前端 未结 8 1767
轻奢々
轻奢々 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:39

    I know the OP is asking for a mysql answer but since I found the other answers not working for me,

    • Most of them fail with order by
    • Or they are simply very inefficient and make your query very slow for a fat table

    So to save time for others like me, just index the row after retrieving them from database

    example in PHP:

    $users = UserRepository::loadAllUsersAndSortByScore();
    
    foreach($users as $index=>&$user){
        $user['rank'] = $index+1;
    }
    

    example in PHP using offset and limit for paging:

    $limit = 20; //page size
    $offset = 3; //page number
    
    $users = UserRepository::loadAllUsersAndSortByScore();
    
    foreach($users as $index=>&$user){
        $user['rank'] = $index+1+($limit*($offset-1));
    }
    

提交回复
热议问题